There are npiles 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 ith 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 exactlykcoins 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.
We define \(f[i][j]\) as the maximum value sum of taking \(j\) coins from the first \(i\) piles. The answer is \(f[n][k]\), where \(n\) is the number of piles.
For the \(i\)-th pile, we can choose to take the first \(0\), \(1\), \(2\), \(\cdots\), \(k\) coins. We can use a prefix sum array \(s\) to quickly calculate the value sum of taking the first \(h\) coins.
where \(0 \leq h \leq j\), and \(s[h]\) represents the value sum of taking the first \(h\) coins from the \(i\)-th pile.
The time complexity is \(O(k \times L)\), and the space complexity is \(O(n \times k)\). Here, \(L\) is the total number of coins, and \(n\) is the number of piles.
We can observe that for the \(i\)-th pile, we only need to use \(f[i - 1][j]\) and \(f[i][j - h]\), so we can optimize the two-dimensional array to a one-dimensional array.
The time complexity is \(O(k \times L)\), and the space complexity is \(O(k)\).