[LeetCode] Maximum Value of K Coins From Piles

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
int dp[1001][2001];
int helper(vector<vector<int>>& p, int k, int c) {
if(c == p.size()) return 0;
if(dp[c][k] != -1) return dp[c][k];
dp[c][k] = helper(p,k,c+1);
for(int i = 0; i < p[c].size() and i + 1 <= k; i++) {
dp[c][k] = max(dp[c][k], helper(p,k-i-1,c+1) + p[c][i]);
}
return dp[c][k];
}
public:
int maxValueOfCoins(vector<vector<int>>& piles, int k) {
int n = piles.size();
for(int i = 0; i < n; i++) {
int base = 0;
for(int j = 0; j < piles[i].size(); j++) {
base = piles[i][j] += base;
}
}
memset(dp,-1,sizeof(dp));

return helper(piles,k,0);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/28/PS/LeetCode/maximum-value-of-k-coins-from-piles/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.