Maximum Coins Heroes Can Collect — LeetCode 2838 Python Solution

MediumLeetCode PremiumArrayTwo PointersBinary SearchPrefix SumSorting
Problem
#2838
Pattern
Prefix Sum
Reading time
3 min

The problem

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.

Example

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:

Python solution

Python
class Solution:
    def maximumCoins(
        self, heroes: List[int], monsters: List[int], coins: List[int]
    ) -> List[int]:
        m = len(monsters)
        idx = sorted(range(m), key=lambda i: monsters[i])
        s = list(accumulate((coins[i] for i in idx), initial=0))
        ans = []
        for h in heroes:
            i = bisect_right(idx, h, key=lambda i: monsters[i])
            ans.append(s[i])
        return ans

Complexity

MeasureComplexity
TimeO((m + n) \times \log n)
SpaceO(m) auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 2838. Maximum Coins Heroes Can Collect is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2838. Maximum Coins Heroes Can Collect?
LeetCode 2838. Maximum Coins Heroes Can Collect is rated Medium on LeetCode.
What is the time complexity of LeetCode 2838. Maximum Coins Heroes Can Collect?
The Python solution on this page runs in O((m + n) \times \log n).
What is the space complexity of LeetCode 2838. Maximum Coins Heroes Can Collect?
The Python solution on this page uses O(m) auxiliary space.
What topics does LeetCode 2838. Maximum Coins Heroes Can Collect cover?
LeetCode 2838. Maximum Coins Heroes Can Collect is tagged Array, Two Pointers, Binary Search, Prefix Sum and Sorting on LeetCode.
Is LeetCode 2838. Maximum Coins Heroes Can Collect a premium problem?
Yes. LeetCode 2838. Maximum Coins Heroes Can Collect is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview