Maximize Happiness of Selected Children - Sorting [JS]

Description 

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

Popular posts from this blog

Beautiful Towers II - Monotonic Increasing Stack [JS]

Check if There is a Valid Partition For The Array - Two Approaches - DP & Recursion w/ Memoization [JS]

Divide Nodes Into the Maximum Number of Groups - Union Find & BFS [JS]

Count Elements With Maximum Frequency - Hashmap [JS]

Robot Collisions - Stack [JS]