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

Minimum Number of Operations to Sort a Binary Tree by Level - BFS & Cycle Counting Explained [JS]

Beautiful Towers II - Monotonic Increasing Stack [JS]

Reschedule Meetings for Maximum Free Time I - Sliding Window - Constant Space [JS]

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

Sum of Prefix Scores of Strings - Trie [JS]