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/1400-1499/1478.Allocate Mailboxes/README_EN.md
+51-2
Original file line number
Diff line number
Diff line change
@@ -34,7 +34,7 @@ tags:
34
34
<strong>Input:</strong> houses = [1,4,8,10,20], k = 3
35
35
<strong>Output:</strong> 5
36
36
<strong>Explanation:</strong> Allocate mailboxes in position 3, 9 and 20.
37
-
Minimum total distance from each houses to nearest mailboxes is |3-1| + |4-3| + |9-8| + |10-9| + |20-20| = 5
37
+
Minimum total distance from each houses to nearest mailboxes is |3-1| + |4-3| + |9-8| + |10-9| + |20-20| = 5
38
38
</pre>
39
39
40
40
<p><strongclass="example">Example 2:</strong></p>
@@ -61,7 +61,23 @@ Minimum total distance from each houses to nearest mailboxes is |2-3| + |3-3| +
61
61
62
62
<!-- solution:start -->
63
63
64
-
### Solution 1
64
+
### Solution 1: Dynamic Programming
65
+
66
+
We define $f[i][j]$ to represent the minimum total distance between the houses and their nearest mailbox, when placing $j$ mailboxes among the first $i+1$ houses. Initially, $f[i][j] = \infty$, and the final answer will be $f[n-1][k]$.
67
+
68
+
We can iterate over the last house $p$ controlled by the $j-1$-th mailbox, i.e., $0 \leq p \leq i-1$. The $j$-th mailbox will control the houses in the range $[p+1, \dots, i]$. Let $g[i][j]$ denote the minimum total distance when placing a mailbox for the houses in the range $[i, \dots, j]$. The state transition equation is:
69
+
70
+
$$
71
+
f[i][j] = \min_{0 \leq p \leq i-1} \{f[p][j-1] + g[p+1][i]\}
0 commit comments