Maximum Coins Heroes Can Collect - Problem

There is a battle where n heroes are trying to defeat m monsters. You are given two 1-indexed arrays of positive integers heroes and monsters of length n and m, respectively.

heroes[i] is the power of the i-th hero, and monsters[i] is the power of the i-th monster. The i-th hero can defeat the j-th monster if monsters[j] <= heroes[i].

You are also given a 1-indexed array coins of length m consisting of positive integers. coins[i] is the number of coins that each hero earns after defeating the i-th monster.

Return an array ans of length n where ans[i] is the maximum number of coins that the i-th hero can collect from this battle.

Note: The health of a hero doesn't get reduced after defeating a monster. Multiple heroes can defeat a monster, but each monster can be defeated by a given hero only once.

Input & Output

Example 1 — Basic Battle
$ Input: heroes = [1,4,2], monsters = [1,2,3,4], coins = [5,10,15,20]
Output: [5,50,20]
💡 Note: Hero 1 (power 1): defeats monster 1 (power 1) → 5 coins. Hero 2 (power 4): defeats all monsters → 5+10+15+20 = 50 coins. Hero 3 (power 2): defeats monsters 1,2 → 5+10 = 15 coins.
Example 2 — No Defeats
$ Input: heroes = [1,1], monsters = [2,3], coins = [10,20]
Output: [0,0]
💡 Note: Both heroes have power 1, but all monsters have power ≥ 2, so no defeats possible.
Example 3 — All Powerful Hero
$ Input: heroes = [10], monsters = [1,2,3], coins = [5,10,15]
Output: [30]
💡 Note: Hero with power 10 can defeat all monsters (1,2,3) and collect 5+10+15 = 30 coins.

Constraints

  • 1 ≤ heroes.length, monsters.length ≤ 105
  • 1 ≤ heroes[i], monsters[i] ≤ 108
  • 1 ≤ coins[i] ≤ 108

Visualization

Tap to expand
Maximum Coins Heroes Can CollectHeroes142Monsters1234Coins5101520Can defeat M1Can defeat allCan defeat M1,M2Battle Results:Hero 1: 5Hero 2: 50Hero 3: 15Output: [5, 50, 15]
Understanding the Visualization
1
Input
Heroes [1,4,2], Monsters [1,2,3,4], Coins [5,10,15,20]
2
Process
Each hero defeats monsters with power ≤ their own power
3
Output
Total coins each hero collects: [5,50,20]
Key Takeaway
🎯 Key Insight: Sort monsters by power, then use binary search to efficiently find how many each hero can defeat
Asked in
Amazon 25 Google 18 Microsoft 15
28.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen