Skip to content

Commit 00eb3b0

Browse files
authored
Create maximum-value-of-k-coins-from-piles.cpp
1 parent 23e686a commit 00eb3b0

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// Time: O(n * k^2)
2+
// Space: O(k)
3+
4+
// dp
5+
class Solution {
6+
public:
7+
int maxValueOfCoins(vector<vector<int>>& piles, int k) {
8+
vector<int> dp(1);
9+
for (const auto& pile : piles) {
10+
vector<int> new_dp(min(static_cast<int>(size(dp) + size(pile)), k + 1));
11+
for (int i = 0; i < size(dp); ++i) {
12+
for (int j = 0, curr = 0; j <= min(k - i, static_cast<int>(size(pile))); ++j) {
13+
new_dp[i + j] = max(new_dp[i + j], dp[i] + curr);
14+
curr += j < size(pile) ? pile[j] : 0;
15+
}
16+
}
17+
dp = move(new_dp);
18+
}
19+
return dp.back();
20+
}
21+
};

0 commit comments

Comments
 (0)