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 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 exactly k
coins optimally.
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.
解题思路:考虑使用动态规划算法,将当前piles和剩余可选硬币数量作为状态参数。
(一开始的思路有问题,一个一个点去规划,效率比较低,然而最好按照piles进行分叉)
表示目前考虑从第0个(及之后)pile向外拿东西,剩余能拿两次。
把f的结果存储起来得到如下的矩阵:
实现代码如下,ps. key_map[i][coins] != -1的判断非常重要,可以省去重复的计算,否则会超时
class Solution:
def maxValueOfCoins(self, piles: List[List[int]], k: int) -> int:
N = len(piles)
key_map = [[-1]*(k+1) for _ in range(N)]
def find (i,coins):
if i == N: #out of range
return 0
if key_map[i][coins] != -1:
return key_map[i][coins]
#skip the pile
key_map[i][coins] = find(i+1,coins)
#do not skip, find the max
curPile = 0
for j in range(min(coins, len(piles[i]))):
curPile += piles[i][j]
key_map[i][coins] = max(key_map[i][coins], curPile + find(i+1,coins-j-1))
return key_map[i][coins]
return find(0,k)