Skip to content

Commit 8548592

Browse files
authored
Update 1478-allocate-mailboxes.js
1 parent 0ce2abe commit 8548592

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

1478-allocate-mailboxes.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,3 +24,39 @@ const minDistance = function (A, K) {
2424
}
2525
return dp[n - 1]
2626
}
27+
28+
// another
29+
30+
/**
31+
* @param {number[]} houses
32+
* @param {number} k
33+
* @return {number}
34+
*/
35+
function minDistance(houses, k) {
36+
const n = houses.length, { abs, min } = Math, INF = Infinity
37+
houses.sort((a, b) => a - b)
38+
const costs = Array.from({ length: 100 }, () => Array(100).fill(0))
39+
const memo = Array.from({ length: 100 }, () => Array(100).fill(null))
40+
41+
for(let i = 0; i < n; i++) {
42+
for(let j = 0; j < n; j++) {
43+
const mid = houses[~~((i + j) >> 1)]
44+
for (let k = i; k <= j; k++) costs[i][j] += abs(mid - houses[k])
45+
}
46+
}
47+
48+
return dp(k, 0)
49+
50+
function dp(k, i) {
51+
if (k === 0 && i === n) return 0
52+
if (k === 0 || i === n) return INF
53+
if (memo[k][i] != null) return memo[k][i]
54+
let res = INF
55+
for (let j = i; j < n; j++) {
56+
res = min(res, costs[i][j] + dp(k - 1, j + 1))
57+
}
58+
59+
return memo[k][i] = res
60+
}
61+
}
62+

0 commit comments

Comments
 (0)