You are currently designing a dynamic array. You are given a 0-indexed integer array nums, where nums[i] is the number of elements that will be in the array at time i. In addition, you are given an integer k, the
maximum number of times you can resize the array (toany size).
The size of the array at time t, sizet, must be at least nums[t] because there needs to be enough space in the array to hold all the elements. The
space wasted at time t is defined as sizet - nums[t], and the
total space wasted is the sum of the space wasted across every time
t where 0 <= t < nums.length.
Return theminimumtotal space wasted if you can resize the array at mostktimes.
Note: The array can have any size at the start and doesnot count towards the number of resizing operations.
Input: nums =[10,20,30], k =1Output: 10Explanation: size =[20,20,30].We can set the initial size to be 20 and resize to 30 at time 2.The total wasted space is(20-10)+(20-20)+(30-30)=10.
Input: nums =[10,20,15,30,20], k =2Output: 15Explanation: size =[10,20,20,30,30].We can set the initial size to 10, resize to 20 at time 1, and resize to 30 at time 3.The total wasted space is(10-10)+(20-20)+(20-15)+(30-30)+(30-20)=15.
We want to minimize wasted space by optimally partitioning the array into at most k+1 segments, each with a fixed size. For each segment, the best size is the maximum value in that segment. We use DP to try all possible partitions efficiently.
classSolution {
funminSpaceWastedKResizing(nums: IntArray, k: Int): Int {
val n = nums.size
val dp = Array(n+1) { IntArray(k+2) { Int.MAX_VALUE } }
dp[0][0] = 0for (i in1..n) {
for (j in0..k) {
var mx = 0var sum = 0for (l in i downTo 1) {
mx = maxOf(mx, nums[l-1])
sum += nums[l-1]
if (dp[l-1][j] !=Int.MAX_VALUE)
dp[i][j+1] = minOf(dp[i][j+1], dp[l-1][j] + mx * (i-l+1) - sum)
}
}
}
var ans = Int.MAX_VALUE
for (j in1..k+1) ans = minOf(ans, dp[n][j])
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from typing import List
classSolution:
defminSpaceWastedKResizing(self, nums: List[int], k: int) -> int:
n = len(nums)
dp = [[float('inf')] * (k+2) for _ in range(n+1)]
dp[0][0] =0for i in range(1, n+1):
for j in range(k+1):
mx, s =0, 0for l in range(i, 0, -1):
mx = max(mx, nums[l-1])
s += nums[l-1]
if dp[l-1][j] != float('inf'):
dp[i][j+1] = min(dp[i][j+1], dp[l-1][j] + mx * (i-l+1) - s)
return min(dp[n][1:])
impl Solution {
pubfnmin_space_wasted_k_resizing(nums: Vec<i32>, k: i32) -> i32 {
let n = nums.len();
let k = k asusize;
letmut dp =vec![vec![i32::MAX; k+2]; n+1];
dp[0][0] =0;
for i in1..=n {
for j in0..=k {
letmut mx =0;
letmut sum =0;
for l in (1..=i).rev() {
mx = mx.max(nums[l-1]);
sum += nums[l-1];
if dp[l-1][j] !=i32::MAX {
dp[i][j+1] = dp[i][j+1].min(dp[l-1][j] + mx * (i-l+1) - sum);
}
}
}
}
letmut ans =i32::MAX;
for j in1..=k+1 { ans = ans.min(dp[n][j]); }
ans
}
}