|
| 1 | +/** |
| 2 | + * 1478. Allocate Mailboxes |
| 3 | + * https://leetcode.com/problems/allocate-mailboxes/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * Given the array houses where houses[i] is the location of the ith house along a street and |
| 7 | + * an integer k, allocate k mailboxes in the street. |
| 8 | + * |
| 9 | + * Return the minimum total distance between each house and its nearest mailbox. |
| 10 | + * |
| 11 | + * The test cases are generated so that the answer fits in a 32-bit integer. |
| 12 | + */ |
| 13 | + |
| 14 | +/** |
| 15 | + * @param {number[]} houses |
| 16 | + * @param {number} k |
| 17 | + * @return {number} |
| 18 | + */ |
| 19 | +var minDistance = function(houses, k) { |
| 20 | + houses.sort((a, b) => a - b); |
| 21 | + const n = houses.length; |
| 22 | + const cache = new Map(); |
| 23 | + |
| 24 | + return findMinDistance(0, k); |
| 25 | + |
| 26 | + function medianDistance(start, end) { |
| 27 | + let sum = 0; |
| 28 | + const mid = Math.floor((start + end) / 2); |
| 29 | + for (let i = start; i <= end; i++) { |
| 30 | + sum += Math.abs(houses[i] - houses[mid]); |
| 31 | + } |
| 32 | + return sum; |
| 33 | + } |
| 34 | + |
| 35 | + function findMinDistance(index, mailboxes) { |
| 36 | + if (index === n) return mailboxes === 0 ? 0 : Infinity; |
| 37 | + if (mailboxes === 0) return Infinity; |
| 38 | + |
| 39 | + const key = `${index}:${mailboxes}`; |
| 40 | + if (cache.has(key)) return cache.get(key); |
| 41 | + |
| 42 | + let minDist = Infinity; |
| 43 | + for (let j = index; j < n && n - j >= mailboxes; j++) { |
| 44 | + const distance = medianDistance(index, j) + findMinDistance(j + 1, mailboxes - 1); |
| 45 | + minDist = Math.min(minDist, distance); |
| 46 | + } |
| 47 | + |
| 48 | + cache.set(key, minDist); |
| 49 | + return minDist; |
| 50 | + } |
| 51 | +}; |
0 commit comments