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

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]