DEV Community

Karleb
Karleb

Posted on

#3075. Maximize Happiness of Selected Children

https://leetcode.com/problems/maximize-happiness-of-selected-children/?envType=daily-question&envId=2024-05-09

/**
 * @param {number[]} happiness
 * @param {number} k
 * @return {number}
 */
var maximumHappinessSum = function (happiness, k) {
    let res = 0
    happiness.sort((a, b) => b - a)

    for (let i = 0; i < k; i++) {
        res += Math.max(happiness[i] - i, 0)
    }

    return res
};

Enter fullscreen mode Exit fullscreen mode

One tip from this question is:

Math.max(happiness[i] - i, 0)
Enter fullscreen mode Exit fullscreen mode

Subtracting the value from it's index and making the results that are less than 0 to be 0 just solves the question.

Still feels like magic to me.

Top comments (0)