Maximum Value of K Coins From Piles — LeetCode 2218 Python Solution
HardArrayDynamic ProgrammingPrefix Sum
- Problem
- #2218
- Pattern
- 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
Python
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
| Measure | Complexity |
|---|---|
| Time | O(k \times L) |
| Space | O(n \times k) auxiliary |
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 \times 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 \times 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.