Minimum Total Space Wasted With K Resizing Operations — LeetCode 1959 Python Solution
- Problem
- #1959
- Pattern
- Dynamic Programming
- Reading time
- 3 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O(n^2 \times k) |
| Space | O(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.