Taro Logo

Maximum Coins Heroes Can Collect

Medium
Asked by:
Deutsche Bank
1 view
Topics:
ArraysBinary Search

There is a battle and 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 ith hero, and monsters[i] is the power of ith monster.

The ith hero can defeat the jth 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 ith monster.

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

Notes

  • 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.

Example 1:

Input: heroes = [1,4,2], monsters = [1,1,5,2,3], coins = [2,3,4,5,6]
Output: [5,16,10]
Explanation: For each hero, we list the index of all the monsters he can defeat:
1st hero: [1,2] since the power of this hero is 1 and monsters[1], monsters[2] <= 1. So this hero collects coins[1] + coins[2] = 5 coins.
2nd hero: [1,2,4,5] since the power of this hero is 4 and monsters[1], monsters[2], monsters[4], monsters[5] <= 4. So this hero collects coins[1] + coins[2] + coins[4] + coins[5] = 16 coins.
3rd hero: [1,2,4] since the power of this hero is 2 and monsters[1], monsters[2], monsters[4] <= 2. So this hero collects coins[1] + coins[2] + coins[4] = 10 coins.
So the answer would be [5,16,10].

Example 2:

Input: heroes = [5], monsters = [2,3,1,2], coins = [10,6,5,2]
Output: [23]
Explanation: This hero can defeat all the monsters since monsters[i] <= 5. So he collects all of the coins: coins[1] + coins[2] + coins[3] + coins[4] = 23, and the answer would be [23].

Example 3:

Input: heroes = [4,4], monsters = [5,7,8], coins = [1,1,1]
Output: [0,0]
Explanation: In this example, no hero can defeat a monster. So the answer would be [0,0],

Constraints:

  • 1 <= n == heroes.length <= 105
  • 1 <= m == monsters.length <= 105
  • coins.length == m
  • 1 <= heroes[i], monsters[i], coins[i] <= 109

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What are the lengths of the monster health, hero power, and coin reward arrays, and are they guaranteed to be of the same length?
  2. Can hero powers, monster health values, or coin rewards be negative or zero, or are they strictly positive integers?
  3. If a hero can defeat multiple monsters, do they collect the coin reward for each individual monster defeated?
  4. Should the resulting array of coins maintain the exact same relative order as the input heroes array?
  5. What should be returned for a hero if their power level is too low to defeat any of the available monsters?

Brute Force Solution

Approach

Imagine you have a group of heroes and a group of monsters, each with their own strength and holding a certain amount of coins. The brute force approach checks every possible monster each hero could potentially fight to see how many coins they can collect.

Here's how the algorithm would work step-by-step:

  1. Look at the first hero in your group.
  2. Compare this hero's strength against the strength of every single monster one by one.
  3. Every time you find a monster that is weak enough for this hero to defeat, add the coins that monster is holding to a running total for this hero.
  4. Keep going until this hero has checked every single monster.
  5. Once you have checked all monsters for the first hero, write down their total collected coins.
  6. Move on to the next hero and repeat the exact same process of checking every single monster again.
  7. Do this for every single hero in the group.
  8. Finally, gather all the written totals so you know exactly how many coins each hero managed to collect.

Code Implementation

def maximum_coins_brute_force(hero_strengths, monster_strengths, monster_coins):
    collected_coins_list = []

    # Iterate through every single hero to calculate their individual total coins
    for current_hero in hero_strengths:
        total_hero_coins = 0

        # Check every monster against the current hero to see if the hero can win
        for current_monster in range(len(monster_strengths)):
            if current_hero >= monster_strengths[current_monster]:
                total_hero_coins += monster_coins[current_monster]

        collected_coins_list.append(total_hero_coins)

    # Gather all collected totals into a final list matching the heroes
    return collected_coins_list

Big(O) Analysis

Time Complexity
O(h * m) – For each of the h heroes in the group, we iterate through all m monsters to check their strengths and accumulate coins. This means the first hero checks m monsters, the second hero checks m monsters, and so on for all heroes. This leads to approximately h times m operations, which simplifies to O(h * m).
Space Complexity
O(H) – To store the final results for every hero, the algorithm maintains an auxiliary results array whose size is directly proportional to the number of heroes. Assuming H represents the number of heroes and M represents the number of monsters, we allocate space for H total coin totals. No other data structures or recursive calls are utilized since the running totals are updated in place for each hero. Therefore, the auxiliary space complexity simplifies to O(H) to hold the output coin collection for each hero.

Optimal Solution

Approach

To efficiently figure out how many coins each hero can collect, we first organize the heroes and monsters in a logical order by their strength. By keeping a running total of the coins collected so far as we consider progressively stronger heroes, we can quickly answer each hero's potential without restarting our counting from scratch.

Here's how the algorithm would work step-by-step:

  1. Gather all the heroes and monsters together and sort them in a line based on their strength, moving from the weakest to the strongest.
  2. Create a running scorecard that tracks the total number of coins collected as we encounter monsters along the strength line.
  3. Pair each hero with the monsters they are strong enough to defeat, noting the total coins those specific monsters are holding.
  4. Since a stronger hero can automatically defeat everything a weaker hero can plus potentially more, update the stronger hero's coin total by carrying over the previous hero's total earnings.
  5. Continue this process for all heroes in order so that each person instantly knows their maximum possible earnings by looking at the running scorecard.
  6. Return the final list of coin totals matching the original order of the heroes so everyone gets their correct reward.

Code Implementation

def maximum_coins_heroes_can_collect(hero_strengths, monster_strengths, monster_coins):
    # Combine original indices with heroes to preserve the initial order after sorting.
    indexed_heroes = []
    for hero_index, strength in enumerate(hero_strengths):
        indexed_heroes.append((strength, hero_index))

    monsters = list(zip(monster_strengths, monster_coins))

    indexed_heroes.sort()
    monsters.sort()

    maximum_coins_result = [0] * len(hero_strengths)
    monster_pointer = 0
    accumulated_coins = 0

    # Iterate through sorted heroes to assign accumulated coins based on defeated monsters.
    for hero_strength, hero_index in indexed_heroes:
        while monster_pointer < len(monsters) and monsters[monster_pointer][0] <= hero_strength:
            accumulated_coins += monsters[monster_pointer][1]
            monster_pointer += 1
        maximum_coins_result[hero_index] = accumulated_coins

    # Return final results mapped back to the original order of the heroes.
    return maximum_coins_result

Big(O) Analysis

Time Complexity
O(n log n) – The primary cost is driven by sorting both the heroes and the monsters based on their strength, which takes O(n log n) time where n is the combined number of heroes and monsters. Afterwards, we iterate through the sorted monsters and heroes in a single linear pass to accumulate the running coin totals, requiring O(n) time. Combining the dominant sorting step with the linear traversal, the total operations approximate n log n plus n, which simplifies to the final Big O time complexity of O(n log n).
Space Complexity
O(n + m) – The auxiliary space is driven by the structures used to store and sort the heroes and monsters, where n represents the number of heroes and m represents the number of monsters. We create combined objects or index arrays to sort both entities and map their original positions, which requires memory proportional to the total number of inputs. Additionally, an output array of size n is required to store the final coin totals matching the original order of the heroes. Therefore, the total extra memory scales linearly with the combined input size of heroes and monsters.

Edge Cases

Empty monster or hero arrays
How to Handle:
Return an empty array immediately because no heroes exist to collect coins or no monsters are available to defeat.
Heroes have power levels strictly lower than all monster healths
How to Handle:
Return an array of zeros since no hero can defeat any monster to earn coins.
Monster healths, power levels, or coin values contain very large integers
How to Handle:
Use 64-bit integer types for accumulating coins to prevent potential arithmetic overflow during summation.
Arrays contain duplicate power levels or monster health values
How to Handle:
Sort the heroes while preserving their original indices and group identical power levels to avoid redundant calculations.
Maximum-sized inputs with millions of monsters and heroes
How to Handle:
Use efficient sorting combined with prefix sums and binary search instead of nested loops to achieve optimal time complexity.
All monsters have health values of zero or negative numbers
How to Handle:
Filter or validate input ranges beforehand to ensure game logic constraints are respected.
Monsters have zero coin rewards
How to Handle:
The algorithm accumulates zero coins correctly as the prefix sums will not increase when defeating those monsters.