Skip to content

Commit ceee262

Browse files
authored
Create 1959-minimum-total-space-wasted-with-k-resizing-operations.js
1 parent c2123be commit ceee262

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} k
4+
* @return {number}
5+
*/
6+
const minSpaceWastedKResizing = function(nums, k) {
7+
const n = nums.length, INF = 200 * 1e6;
8+
const memo = Array.from({ length: 200 }, () => Array(200));
9+
return dp(nums, 0, k);
10+
function dp(nums, i, k) {
11+
if (i === n) return 0;
12+
if (k === -1) return INF;
13+
if (memo[i][k] != null) return memo[i][k];
14+
let ans = INF, maxNum = nums[i], totalSum = 0;
15+
for (let j = i; j < n; j++) {
16+
maxNum = Math.max(maxNum, nums[j]);
17+
totalSum += nums[j];
18+
const wasted = maxNum * (j - i + 1) - totalSum;
19+
ans = Math.min(ans, dp(nums, j + 1, k - 1) + wasted);
20+
}
21+
return memo[i][k] = ans;
22+
}
23+
};
24+

0 commit comments

Comments
 (0)