Maximum Value of K Coins From Piles Problem
Description
LeetCode Problem 2218.
There are n piles of coins on a table. Each pile consists of a positive number of coins of assorted denominations.
In one move, you can choose any coin on top of any pile, remove it, and add it to your wallet.
Given a list piles, where piles[i] is a list of integers denoting the composition of the i^th pile from top to bottom, and a positive integer k, return the maximum total value of coins you can have in your wallet if you choose exactly k coins optimally.
Example 1:

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.
The maximum total we can obtain is 101.
Example 2:
Input: piles = [[100],[100],[100],[100],[100],[100],[1,1,1,1,1,1,700]], k = 7
Output: 706
Explanation:
The maximum total can be obtained if we choose all coins from the last pile.
Constraints:
n == piles.length1 <= n <= 10001 <= piles[i][j] <= 10^51 <= k <= sum(piles[i].length) <= 2000
Solution
Approach: Dynamic Programming (Grouped Knapsack)
Let f[i][j] be the maximum value of j coins taken from the first i piles. From each pile we can only take a prefix of coins, so for pile i we try every prefix length h, using a prefix-sum array s so that s[h] is the value of its first h coins:
f[i][j] = max(f[i-1][j-h] + s[h]) for 0 <= h <= min(j, size of pile i)
The answer is f[n][k].
Complexity: O(k · L) time and O(n · k) space, where L is the total number of coins and n the number of piles.
from itertools import accumulate
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]