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

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]