Maximum Coins Heroes Can Collect - Problem
โ๏ธ Maximum Coins Heroes Can Collect
Imagine an epic battle where n brave heroes face off against m fearsome monsters to collect precious coins! Each hero has a specific power level, and each monster guards a treasure of coins.
The Rules:
- A hero can defeat a monster only if the hero's power is greater than or equal to the monster's power
- Each hero can defeat multiple monsters, but can only defeat each monster once
- Heroes don't lose health after battles - they can keep fighting!
- Multiple heroes can defeat the same monster (but each hero gets coins only once per monster)
Your Goal: For each hero, calculate the maximum coins they can collect by strategically choosing which monsters to defeat.
Input:
heroes[i]- power of the i-th heromonsters[j]- power of the j-th monstercoins[j]- coins earned for defeating the j-th monster
Output: An array where result[i] is the maximum coins the i-th hero can collect.
Input & Output
example_1.py โ Basic Test Case
$
Input:
heroes = [1, 4, 2], monsters = [1, 2, 3], coins = [1, 2, 3]
โบ
Output:
[1, 6, 3]
๐ก Note:
Hero 1 (power=1) can defeat monster 1 (power=1) โ 1 coin. Hero 2 (power=4) can defeat all monsters (1,2,3) โ 1+2+3 = 6 coins. Hero 3 (power=2) can defeat monsters 1,2 โ 1+2 = 3 coins.
example_2.py โ Heroes with Same Power
$
Input:
heroes = [5, 5], monsters = [2, 3, 7], coins = [1, 2, 4]
โบ
Output:
[3, 3]
๐ก Note:
Both heroes have power 5, so both can defeat monsters with power 2 and 3, earning 1+2 = 3 coins each. Neither can defeat the monster with power 7.
example_3.py โ Edge Case - Weak Heroes
$
Input:
heroes = [1, 1], monsters = [5, 10], coins = [10, 20]
โบ
Output:
[0, 0]
๐ก Note:
Both heroes have power 1, but all monsters have higher power (5, 10), so no hero can defeat any monster. Each hero collects 0 coins.
Constraints
- 1 โค n, m โค 105
- 1 โค heroes[i], monsters[i], coins[i] โค 105
- All arrays are 0-indexed in implementation
Visualization
Tap to expand
Understanding the Visualization
1
Assess the Battlefield
Heroes survey all monsters and their rewards
2
Sort by Difficulty
Arrange monsters from weakest to strongest for strategic planning
3
Calculate Cumulative Rewards
Build a prefix sum to know total coins up to any point
4
Find Each Hero's Limit
Use binary search to find the strongest monster each hero can defeat
5
Collect Maximum Coins
Each hero collects coins from all defeatable monsters
Key Takeaway
๐ฏ Key Insight: By sorting monsters and using binary search with prefix sums, we transform an O(nรm) brute force solution into an efficient O((n+m) log m) algorithm that scales beautifully!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code