2218. Maximum Value of K Coins From Piles

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进行分叉)

f(0,2)表示目前考虑从第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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值