Maximize Happiness of Selected Children - Sorting [JS]
Solution: Sorting
It's optimal to pick the k
children with the greatest happiness.
Sort happiness in desc order and pick the first k
children.
At each turn i
, subtract i
from happiness[i]
.
Time Complexity: O(n log(n))
Space Complexity: O(log(n))
(space for sorting)
var maximumHappinessSum = function(happiness, k) {
happiness.sort((a, b) => b - a);
let ans = 0;
for (let i = 0; i < k; i++) {
ans += Math.max(0, happiness[i] - i);
}
return ans;
};
Comments
Post a Comment