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.
Input: piles = [[1,100,3],[7,8,9]], k = 2Output: 101Explanation: The above diagram shows the different ways we can choose k coins. The maximum total we can obtain is 101.
Input: piles = [[100],[100],[100],[100],[100],[100],[1,1,1,1,1,1,700]], k = 7Output: 706Explanation: The maximum total can be obtained if we choose all coins from the last pile.
class Solution: # Time: O(total_coins * k) # Space: O(k) def max_value_of_coins(self, piles: list[list[int]], k: int) -> int: dp = [0] * (k + 1) for pile in piles: prefix = [0] for value in pile: prefix.append(prefix[-1] + value) new_dp = dp[:] for taken in range(1, k + 1): best = new_dp[taken] for use in range(min(taken, len(prefix) - 1) + 1): candidate = dp[taken - use] + prefix[use] if candidate > best: best = candidate new_dp[taken] = best dp = new_dp return dp[k]