|
| 1 | +/** |
| 2 | + * 1959. Minimum Total Space Wasted With K Resizing Operations |
| 3 | + * https://leetcode.com/problems/minimum-total-space-wasted-with-k-resizing-operations/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are currently designing a dynamic array. You are given a 0-indexed integer array nums, |
| 7 | + * where nums[i] is the number of elements that will be in the array at time i. In addition, |
| 8 | + * you are given an integer k, the maximum number of times you can resize the array (to any size). |
| 9 | + * |
| 10 | + * The size of the array at time t, sizet, must be at least nums[t] because there needs to be |
| 11 | + * enough space in the array to hold all the elements. The space wasted at time t is defined |
| 12 | + * as sizet - nums[t], and the total space wasted is the sum of the space wasted across every |
| 13 | + * time t where 0 <= t < nums.length. |
| 14 | + * |
| 15 | + * Return the minimum total space wasted if you can resize the array at most k times. |
| 16 | + * |
| 17 | + * Note: The array can have any size at the start and does not count towards the number of |
| 18 | + * resizing operations. |
| 19 | + */ |
| 20 | + |
| 21 | +/** |
| 22 | + * @param {number[]} nums |
| 23 | + * @param {number} k |
| 24 | + * @return {number} |
| 25 | + */ |
| 26 | +var minSpaceWastedKResizing = function(nums, k) { |
| 27 | + const n = nums.length; |
| 28 | + const dp = new Array(n + 1).fill().map(() => new Array(k + 2).fill(Infinity)); |
| 29 | + dp[0][0] = 0; |
| 30 | + |
| 31 | + for (let i = 1; i <= n; i++) { |
| 32 | + let maxVal = 0; |
| 33 | + let sum = 0; |
| 34 | + |
| 35 | + for (let j = i; j > 0; j--) { |
| 36 | + maxVal = Math.max(maxVal, nums[j - 1]); |
| 37 | + sum += nums[j - 1]; |
| 38 | + const waste = maxVal * (i - j + 1) - sum; |
| 39 | + |
| 40 | + for (let resizes = 0; resizes <= k; resizes++) { |
| 41 | + if (dp[j - 1][resizes] !== Infinity) { |
| 42 | + dp[i][resizes + 1] = Math.min(dp[i][resizes + 1], dp[j - 1][resizes] + waste); |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + let result = Infinity; |
| 49 | + for (let resizes = 1; resizes <= k + 1; resizes++) { |
| 50 | + result = Math.min(result, dp[n][resizes]); |
| 51 | + } |
| 52 | + |
| 53 | + return result; |
| 54 | +}; |
0 commit comments