Mice and Cheese - Greedy w/ Sorting [JS]

Description 

Solution: Greedy w/ Sorting

The first mouse should always take the k cheese with the maximum difference (reward1[i] - reward2[i]).
This ensures the loss is minimal.

Time Complexity: O(n log(n))
Space Complexity: O(n)

var miceAndCheese = function(reward1, reward2, k) {
  let n = reward1.length, rewards = [];
  for (let i = 0; i < n; i++) {
    rewards.push([reward1[i], reward2[i], reward1[i] - reward2[i]]);
  }
  rewards.sort((a, b) => b[2] - a[2]);
  let score = 0;
  for (let i = 0; i < n; i++) {
    score += i < k ? rewards[i][0] : rewards[i][1];
  }
  return score;
};

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]