Talentd
FleetCode
Make and follow sheets.Sign in

Minimum Total Space Wasted With K Resizing Operations solution and explanation

MediumArrayDynamic Programming8 min read44.6% acceptanceUpdated 9 Apr 2026
Leetcode 1959. Minimum Total Space Wasted With K Resizing Operations | C++ | in HINDINitesh Kumar · 22:13 · 1K viewsWatch on YouTube
3 more videos on this problem
  1. Leetcode 1959. Minimum Total Space Wasted With K Resizing Operations | C++ | in HINDINitesh Kumar · 22:13 · 1K views
  2. LeetCode 1959. Minimum Total Space Wasted With K Resizing OperationsHappy Coding · 23:42 · 1K views
  3. 1959. Minimum Total Space Wasted With K Resizing Operations (Leetcode Medium)Programming Live with Larry · 24:38 · 794 views
  4. 【每日一题】1959. Minimum Total Space Wasted With K Resizing Operations, 8/17/2021Huifeng Guan · 28:09 · 618 views

The problem

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.

Example 1:

Input: nums = [10,20], k = 0
Output: 10
Explanation: size = [20,20].
We can set the initial size to be 20.
The total wasted space is (20 - 10) + (20 - 20) = 10.

Example 2:

Input: nums = [10,20,30], k = 1
Output: 10
Explanation: 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.

Example 3:

Input: nums = [10,20,15,30,20], k = 2
Output: 15
Explanation: 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.

Constraints:

  • 1 <= nums.length <= 200
  • 1 <= nums[i] <= 106
  • 0 <= k <= nums.length - 1

Approach overview

Problem Overview: You receive an array nums where each value represents the number of elements stored at a time step. The array capacity can be resized at most k times. Each segment must allocate capacity equal to the maximum value in that segment. The goal is to minimize the total unused space across the entire sequence.

Approach 1: Greedy Capacity Expansion (Approximate) (Time: O(n^2), Space: O(1))

This idea grows segments greedily while tracking the current maximum element. For every starting index, extend the segment forward and compute wasted space as max_value * length - sum. The greedy intuition is that increasing capacity only when necessary reduces resizing operations. However, this strategy does not always guarantee the global minimum waste because early greedy choices may force inefficient capacity later. It works as a baseline and helps visualize how segment capacity determines waste.

Approach 2: Dynamic Programming with Partitioning (Optimal) (Time: O(n^2 * k), Space: O(n * k))

This approach models the problem as partitioning the array into at most k + 1 segments. Define dp[i][j] as the minimum wasted space for the first i elements using j resizing operations. For each state, iterate backward to form the last segment ending at i, while maintaining the segment's maximum value and cumulative sum. The wasted space for that segment is computed in constant time during the iteration. Transition: dp[i][j] = min(dp[p][j-1] + waste(p+1..i)). This partition-based DP ensures every possible segmentation is evaluated efficiently.

The key observation: once a segment's capacity is fixed to its maximum element, every other value contributes predictable unused space. By iterating backward and updating the running maximum, the cost of each candidate segment can be computed without extra preprocessing.

This technique is a classic example of segmentation DP where the array is split into optimal groups. Problems involving partitioning arrays with minimized cost frequently use dynamic programming over prefixes combined with scanning segments. The input itself is a sequential structure, so operations revolve around scanning the array and maintaining segment statistics.

Recommended for interviews: Dynamic Programming with partitioning. Interviewers expect you to recognize the segmentation pattern and construct a dp[i][k] state. Starting with the greedy intuition helps explain the cost calculation, but the DP solution demonstrates strong problem decomposition and optimization skills.

Approach 1: Dynamic Programming with Partitioning

This approach involves using dynamic programming to solve the problem of minimizing space wasted by partitioning the array into subarrays. Each subarray has a uniform size that is at least the maximum of the subarray's elements. Work through the subarrays and decide the partition points based on available resizing operations (k) and minimize the total space wasted.

def minSpaceWastedKResizing(nums, k):
    n = len(nums)
    dp = [[float('inf')] * (k + 1) for _ in range(n)]
    
    for i in range(n):
        current_max = nums[i]
        dp[i][0] = 0
        for j in range(i, -1, -1):
            current_max = max(current_max, nums[j])
            space_waste = current_max * (i - j + 1) - sum(nums[j:i+1])
            for m in range(k + 1):
                if j == 0:
                    dp[i][m] = min(dp[i][m], space_waste)
                elif m > 0:
                    dp[i][m] = min(dp[i][m], dp[j - 1][m - 1] + space_waste)
    return min(dp[-1])

# Example usage
nums = [10, 20, 15, 30, 20]
k = 2
print(minSpaceWastedKResizing(nums, k))  # Output: 15
#include <iostream>
#include <vector>
#include <algorithm>

int minSpaceWastedKResizing(std::vector<int>& nums, int k) {
    int n = nums.size();
    std::vector<std::vector<int>> dp(n, std::vector<int>(k + 1, INT_MAX));
    
    for (int i = 0; i < n; ++i) {
        int current_max = nums[i];
        dp[i][0] = 0;
        for (int j = i; j >= 0; --j) {
            current_max = std::max(current_max, nums[j]);
            int space_waste = current_max * (i - j + 1) - std::accumulate(nums.begin() + j, nums.begin() + i + 1, 0);
            for (int m = 0; m <= k; ++m) {
                if (j == 0) {
                    dp[i][m] = std::min(dp[i][m], space_waste);
                } else if (m > 0) {
                    dp[i][m] = std::min(dp[i][m], dp[j - 1][m - 1] + space_waste);
                }
            }
        }
    }
    return *std::min_element(dp[n - 1].begin(), dp[n - 1].end());
}

int main() {
    std::vector<int> nums = {10, 20, 15, 30, 20};
    int k = 2;
    std::cout << minSpaceWastedKResizing(nums, k) << std::endl;  // Output: 15
    return 0;
}

This Python solution initializes a 2D dp array where dp[i][j] represents the minimum space wasted for the first i elements with j resizings. The solution iteratively computes the space wasted for different segmentations, updating dp values by considering the maximum size needed for each segment. The innermost loop works backward from the current position, testing different starting points for the current portion size-wise.

Complexity

Time Complexity: O(n^2 * k) where n is the number of elements in nums. Space Complexity: O(n * k).

Try this approach in the editor

Approach 2: Greedy Method

This approach uses a greedy strategy, striving to always take the locally optimal configuration regarding resizing at each step. By making locally optimal choices, one can achieve the minimum possible segment space waste.

import java.util.Arrays;

public class Solution {
    public int minSpaceWastedKResizing(int[] nums, int k) {
        int n = nums.length;
        int[][] dp = new int[n][k + 1];
        for (int[] row : dp) Arrays.fill(row, Integer.MAX_VALUE);

        for (int i = 0; i < n; i++) {
            int currentMax = nums[i];
            dp[i][0] = 0;
            for (int j = i; j >= 0; j--) {
                currentMax = Math.max(currentMax, nums[j]);
                int spaceWaste = currentMax * (i - j + 1) - Arrays.stream(nums, j, i + 1).sum();
                for (int m = 0; m <= k; m++) {
                    if (j == 0) {
                        dp[i][m] = Math.min(dp[i][m], spaceWaste);
                    } else if (m > 0) {
                        dp[i][m] = Math.min(dp[i][m], dp[j - 1][m - 1] + spaceWaste);
                    }
                }
            }
        }
        return Arrays.stream(dp[n - 1]).min().getAsInt();
    }

    public static void main(String[] args) {
        Solution sol = new Solution();
        int[] nums = {10, 20, 15, 30, 20};
        int k = 2;
        System.out.println(sol.minSpaceWastedKResizing(nums, k));  // Output: 15
    }
}
function minSpaceWastedKResizing(nums, k) {
    const n = nums.length;
    const dp = Array.from({length: n}, () => Array(k + 1).fill(Infinity));
    
    for (let i = 0; i < n; i++) {
        let current_max = nums[i];
        dp[i][0] = 0;
        for (let j = i; j >= 0; j--) {
            current_max = Math.max(current_max, nums[j]);
            let space_waste = current_max * (i - j + 1) - nums.slice(j, i + 1).reduce((acc, val) => acc + val, 0);
            for (let m = 0; m <= k; m++) {
                if (j === 0) {
                    dp[i][m] = Math.min(dp[i][m], space_waste);
                } else if (m > 0) {
                    dp[i][m] = Math.min(dp[i][m], dp[j - 1][m - 1] + space_waste);
                }
            }
        }
    }
    return Math.min(...dp[n - 1]);
}

// Example usage
const nums = [10, 20, 15, 30, 20];
const k = 2;
console.log(minSpaceWastedKResizing(nums, k));  // Output: 15

In this Java solution, a greedy technique reiterates across input numbers to compute space waste by proactively reallocating constructs to hold segment-wise maximal figures, anchoring at the least total space waste. The most competitive and efficient configuration is derived by sustaining a thorough lookup of resourceful restructuring decisions reflected throughout iterations.

Complexity

Time Complexity: O(n^2 * k), Space Complexity: O(n * k).

Try this approach in the editor

Approach 3: Dynamic Programming

The problem is equivalent to dividing the array nums into k + 1 segments. The wasted space for each segment is the maximum value of that segment multiplied by the length of the segment minus the sum of the elements in that segment. By summing the wasted space of each segment, we get the total wasted space. By adding 1 to k, we are effectively dividing the array into k segments.

Therefore, we define an array g[i][j] to represent the wasted space for the segment nums[i..j], which is the maximum value of nums[i..j] multiplied by the length of nums[i..j] minus the sum of the elements in nums[i..j]. We iterate over i in the range [0, n) and j in the range [i, n), using a variable s to maintain the sum of the elements in nums[i..j] and a variable mx to maintain the maximum value of nums[i..j]. Then we can get:

$ g[i][j] = mx times (j - i + 1) - s

Next, we define f[i][j] to represent the minimum wasted space for dividing the first i elements into j segments. We initialize f[0][0] = 0 and the other positions to infinity. We iterate over i in the range [1, n] and j in the range [1, k], then we iterate over the last element h of the previous j - 1 segments. Then we have:

f[i][j] = min(f[i][j], f[h][j - 1] + g[h][i - 1])

The final answer is f[n][k].

The time complexity is O(n^2 times k), and the space complexity is O(n times (n + k)). Where n is the length of the array nums$.

function minSpaceWastedKResizing(nums: number[], k: number): number {
    k += 1;
    const n = nums.length;
    const g: number[][] = Array.from({ length: n }, () => Array(n).fill(0));

    for (let i = 0; i < n; i++) {
        let s = 0,
            mx = 0;
        for (let j = i; j < n; j++) {
            s += nums[j];
            mx = Math.max(mx, nums[j]);
            g[i][j] = mx * (j - i + 1) - s;
        }
    }

    const inf = Number.POSITIVE_INFINITY;
    const f: number[][] = Array.from({ length: n + 1 }, () => Array(k + 1).fill(inf));
    f[0][0] = 0;

    for (let i = 1; i <= n; i++) {
        for (let j = 1; j <= k; j++) {
            for (let h = 0; h < i; h++) {
                f[i][j] = Math.min(f[i][j], f[h][j - 1] + g[h][i - 1]);
            }
        }
    }

    return f[n][k];
}
func minSpaceWastedKResizing(nums []int, k int) int {
	k++
	n := len(nums)
	g := make([][]int, n)
	for i := range g {
		g[i] = make([]int, n)
	}
	for i := 0; i < n; i++ {
		s, mx := 0, 0
		for j := i; j < n; j++ {
			s += nums[j]
			mx = max(mx, nums[j])
			g[i][j] = mx*(j-i+1) - s
		}
	}
	f := make([][]int, n+1)
	inf := 0x3f3f3f3f
	for i := range f {
		f[i] = make([]int, k+1)
		for j := range f[i] {
			f[i][j] = inf
		}
	}
	f[0][0] = 0
	for i := 1; i <= n; i++ {
		for j := 1; j <= k; j++ {
			for h := 0; h < i; h++ {
				f[i][j] = min(f[i][j], f[h][j-1]+g[h][i-1])
			}
		}
	}
	return f[n][k]
}
impl Solution {
    pub fn min_space_wasted_k_resizing(nums: Vec<i32>, k: i32) -> i32 {
        let mut k = k + 1;
        let n = nums.len();
        let mut g = vec![vec![0; n]; n];

        for i in 0..n {
            let (mut s, mut mx) = (0, 0);
            for j in i..n {
                s += nums[j];
                mx = mx.max(nums[j]);
                g[i][j] = mx * (j as i32 - i as i32 + 1) - s;
            }
        }

        let inf = 0x3f3f3f3f;
        let mut f = vec![vec![inf; (k + 1) as usize]; n + 1];
        f[0][0] = 0;

        for i in 1..=n {
            for j in 1..=k as usize {
                for h in 0..i {
                    f[i][j] = f[i][j].min(f[h][j - 1] + g[h][i - 1]);
                }
            }
        }

        f[n][k as usize]
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Dynamic Programming with Partitioning

Time Complexity: O(n^2 * k) where n is the number of elements in nums. Space Complexity: O(n * k).

Greedy Method

Time Complexity: O(n^2 * k), Space Complexity: O(n * k).

Dynamic Programming–

Complexity analysis

ApproachTimeSpaceWhen to Use
Greedy Capacity ExpansionO(n^2)O(1)Quick heuristic or conceptual baseline for understanding capacity waste
Dynamic Programming with PartitioningO(n^2 * k)O(n * k)General optimal solution when up to k resizes are allowed

Frequently asked questions

Is Minimum Total Space Wasted With K Resizing Operations easy or hard?

The problem is rated Medium on LeetCode with an acceptance rate around 44%. The challenge comes from recognizing the partition DP pattern and efficiently computing the waste for each segment while limiting the number of resizing operations.

Minimum Total Space Wasted With K Resizing Operations Python/Java solution

Python and C++ implementations typically use the dynamic programming partition method with a 2D DP table. Java and JavaScript implementations may demonstrate greedy exploration or the same DP formulation. The optimal version maintains segment maximum values while iterating backward to compute waste efficiently.

How to solve Minimum Total Space Wasted With K Resizing Operations in O(n)?

An O(n) solution is not known for this problem because every possible partition boundary may affect the total waste. The accepted optimal strategy evaluates segment boundaries using dynamic programming, leading to O(n^2 * k) complexity.

What is the best approach for Minimum Total Space Wasted With K Resizing Operations?

Dynamic Programming with partitioning is the optimal approach. The array is divided into at most k+1 segments, and each segment allocates capacity equal to its maximum value. Using a DP state like dp[i][j] (first i elements with j resizes) allows evaluating all valid partitions and computing minimal wasted space efficiently in O(n^2 * k) time.

Is Minimum Total Space Wasted With K Resizing Operations asked at Google/Amazon/Meta?

Dynamic programming segmentation problems similar to this one appear in interviews at companies like Google, Amazon, and Meta. The pattern of splitting an array into optimal partitions with a cost function is common in system optimization and resource allocation questions.

What data structure is used in Minimum Total Space Wasted With K Resizing Operations?

The main structure is a dynamic programming table that stores minimal waste for prefixes of the array. During transitions, simple variables track the running maximum and cumulative sums within each candidate segment of the array.

What is the time complexity of Minimum Total Space Wasted With K Resizing Operations?

The optimal dynamic programming solution runs in O(n^2 * k) time and uses O(n * k) space. For each DP state, the algorithm iterates backward to form candidate segments while maintaining the segment maximum and cumulative waste.

Comments

Now write it yourselfClose this page and solve Minimum Total Space Wasted With K Resizing Operations in the editor, without looking.
Practise Minimum Total Space Wasted With K Resizing Operations