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
- Source
- leetcode.com
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
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
| No. | Problem | Difficulty |
|---|---|---|
| 0689 | Maximum Sum of 3 Non-Overlapping Subarrays | Hard |
| 0813 | Largest Sum of Averages | Medium |
| 1000 | Minimum Cost to Merge Stones | Hard |
| 1140 | Stone Game II | Medium |
| 1444 | Number of Ways of Cutting a Pizza | Hard |
| 1524 | Number of Sub-arrays With Odd Sum | Medium |
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.