HardNo. 2218

Maximum Value of K Coins From Piles — LeetCode 2218 Python Solution

Pattern
Prefix Sum
Topics
Array, Dynamic Programming, Prefix Sum
Reading time
2 min

The problem

There are n piles of coins on a table. Each pile consists of a positive number of coins of assorted denominations.

Example

Input
piles = [[1,100,3],[7,8,9]], k = 2
Output
101
Explanation
The above diagram shows the different ways we can choose k coins.

Python solution

PythonSolution
class Solution:
    def maxValueOfCoins(self, piles: List[List[int]], k: int) -> int:
        n = len(piles)
        f = [[0] * (k + 1) for _ in range(n + 1)]
        for i, nums in enumerate(piles, 1):
            s = list(accumulate(nums, initial=0))
            for j in range(k + 1):
                for h, w in enumerate(s):
                    if j < h:
                        break
                    f[i][j] = max(f[i][j], f[i - 1][j - h] + w)
        return f[n][k]

Complexity

Time
O(k × L)
Space · auxiliary
O(n × k)

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 2218. Maximum Value of K Coins From Piles 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 2218. Maximum Value of K Coins From Piles?

LeetCode 2218. Maximum Value of K Coins From Piles is rated Hard on LeetCode.

What is the time complexity of LeetCode 2218. Maximum Value of K Coins From Piles?

The Python solution on this page runs in O(k × L).

What is the space complexity of LeetCode 2218. Maximum Value of K Coins From Piles?

The Python solution on this page uses O(n × k) auxiliary space.

What topics does LeetCode 2218. Maximum Value of K Coins From Piles cover?

LeetCode 2218. Maximum Value of K Coins From Piles is tagged Array, Dynamic Programming and Prefix Sum on LeetCode.

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.

Free to download. Check it runs on your machine, then pick a plan.