You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardexpand all lines: solution/1900-1999/1959.Minimum Total Space Wasted With K Resizing Operations/README_EN.md
+84-2
Original file line number
Diff line number
Diff line change
@@ -44,7 +44,7 @@ The total wasted space is (20 - 10) + (20 - 20) = 10.
44
44
<strong>Input:</strong> nums = [10,20,30], k = 1
45
45
<strong>Output:</strong> 10
46
46
<strong>Explanation:</strong> size = [20,20,30].
47
-
We can set the initial size to be 20 and resize to 30 at time 2.
47
+
We can set the initial size to be 20 and resize to 30 at time 2.
48
48
The total wasted space is (20 - 10) + (20 - 20) + (30 - 30) = 10.
49
49
</pre>
50
50
@@ -73,7 +73,20 @@ The total wasted space is (10 - 10) + (20 - 20) + (20 - 15) + (30 - 30) + (30 -
73
73
74
74
<!-- solution:start -->
75
75
76
-
### Solution 1
76
+
Solution 1: Dynamic Programming
77
+
The problem is equivalent to dividing the array $\textit{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.
78
+
79
+
Therefore, we define an array $\textit{g}[i][j]$ to represent the wasted space for the segment $\textit{nums}[i..j]$, which is the maximum value of $\textit{nums}[i..j]$ multiplied by the length of $\textit{nums}[i..j]$ minus the sum of the elements in $\textit{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 $\textit{nums}[i..j]$ and a variable $\textit{mx}$ to maintain the maximum value of $\textit{nums}[i..j]$. Then we can get:
80
+
81
+
$$ \textit{g}[i][j] = \textit{mx} \times (j - i + 1) - s $$
82
+
83
+
Next, we define $\textit{f}[i][j]$ to represent the minimum wasted space for dividing the first $i$ elements into $j$ segments. We initialize $\textit{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:
0 commit comments