[LeetCode] Minimum Total Space Wasted With K Resizing Operations

1959. Minimum Total Space Wasted With K Resizing Operations

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 (to any 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 the minimum total space wasted if you can resize the array at most k times.

Note: The array can have any size at the start and does not count towards the number of resizing operations.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
long long dp[222][222];
long long helper(vector<int>& A, int p, int k) {
if(p + k >= A.size()) return 0;
if(k < 0) return INT_MAX;
long long& res = dp[p][k];
if(res != -1) return res;
res = helper(A, p + 1, k - 1);
long long sum = A[p], ma = A[p];
for(int i = p + 1; i < A.size(); i++) {
ma = max(ma, 1ll * A[i]);
sum += A[i];
res = min(res, ma * (i - p + 1) - sum + helper(A,i+1,k-1));
}
return res;
}
public:
int minSpaceWastedKResizing(vector<int>& A, int k) {
memset(dp,-1,sizeof dp);
return helper(A, 0, k + 1);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/13/PS/LeetCode/minimum-total-space-wasted-with-k-resizing-operations/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.