Minimum Total Space Wasted With K Resizing Operations — LeetCode 1959 Python Solution

MediumArrayDynamic Programming
Problem
#1959
Reading time
3 min

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.

Example

Input
nums = [10,20], k = 0
Output
10
Explanation
size = [20,20].

Python solution

Python
class Solution:
    def minSpaceWastedKResizing(self, nums: List[int], k: int) -> int:
        k += 1
        n = len(nums)
        g = [[0] * n for _ in range(n)]
        for i in range(n):
            s = mx = 0
            for j in range(i, n):
                s += nums[j]
                mx = max(mx, nums[j])
                g[i][j] = mx * (j - i + 1) - s
        f = [[inf] * (k + 1) for _ in range(n + 1)]
        f[0][0] = 0
        for i in range(1, n + 1):
            for j in range(1, k + 1):
                for h in range(i):
                    f[i][j] = min(f[i][j], f[h][j - 1] + g[h][i - 1])
        return f[-1][-1]

Complexity

MeasureComplexity
TimeO(n^2 \times k)
SpaceO(n \times (n + k)) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1959. Minimum Total Space Wasted With K Resizing Operations is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1959. Minimum Total Space Wasted With K Resizing Operations?
LeetCode 1959. Minimum Total Space Wasted With K Resizing Operations is rated Medium on LeetCode.
What is the time complexity of LeetCode 1959. Minimum Total Space Wasted With K Resizing Operations?
The Python solution on this page runs in O(n^2 \times k).
What is the space complexity of LeetCode 1959. Minimum Total Space Wasted With K Resizing Operations?
The Python solution on this page uses O(n \times (n + k)) auxiliary space.
What topics does LeetCode 1959. Minimum Total Space Wasted With K Resizing Operations cover?
LeetCode 1959. Minimum Total Space Wasted With K Resizing Operations is tagged Array and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview