Skip to content

Commit 4a42a2c

Browse files
committed
Add solution #1478
1 parent 7b92cb4 commit 4a42a2c

File tree

2 files changed

+53
-1
lines changed

2 files changed

+53
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,322 LeetCode solutions in JavaScript
1+
# 1,323 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -1130,6 +1130,7 @@
11301130
1475|[Final Prices With a Special Discount in a Shop](./solutions/1475-final-prices-with-a-special-discount-in-a-shop.js)|Easy|
11311131
1476|[Subrectangle Queries](./solutions/1476-subrectangle-queries.js)|Medium|
11321132
1477|[Find Two Non-overlapping Sub-arrays Each With Target Sum](./solutions/1477-find-two-non-overlapping-sub-arrays-each-with-target-sum.js)|Medium|
1133+
1478|[Allocate Mailboxes](./solutions/1478-allocate-mailboxes.js)|Hard|
11331134
1480|[Running Sum of 1d Array](./solutions/1480-running-sum-of-1d-array.js)|Easy|
11341135
1481|[Least Number of Unique Integers after K Removals](./solutions/1481-least-number-of-unique-integers-after-k-removals.js)|Medium|
11351136
1486|[XOR Operation in an Array](./solutions/1486-xor-operation-in-an-array.js)|Easy|

solutions/1478-allocate-mailboxes.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
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

Comments
 (0)