Skip to content

Commit a4f6249

Browse files
authored
Create minimum-total-space-wasted-with-k-resizing-operations.cpp
1 parent 099af83 commit a4f6249

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// Time: O(k * n^2)
2+
// Space: O(k * n)
3+
4+
class Solution {
5+
public:
6+
int minSpaceWastedKResizing(vector<int>& nums, int k) {
7+
static const int INF = numeric_limits<int>::max();
8+
9+
++k;
10+
vector<vector<int>> dp(size(nums) + 1, vector<int>(k + 1, INF));
11+
dp[0][0] = 0;
12+
for (int i = 1; i <= size(nums); ++i) {
13+
int total = 0, max_num = 0;
14+
for (int j = i; j >= 1; --j) {
15+
total += nums[j - 1];
16+
max_num = max(max_num, nums[j - 1]);
17+
for (int m = 1; m <= k; ++m) {
18+
if (dp[j - 1][m - 1] != INF) {
19+
dp[i][m] = min(dp[i][m], dp[j - 1][m - 1] + (max_num * (i - j + 1) - total));
20+
}
21+
}
22+
}
23+
}
24+
return dp.back().back();
25+
}
26+
};

0 commit comments

Comments
 (0)