forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
allocate-mailboxes.cpp
31 lines (29 loc) · 929 Bytes
/
allocate-mailboxes.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Time: O(m * n^2)
// Space: O(n)
class Solution {
public:
int minDistance(vector<int>& houses, int k) {
sort(begin(houses), end(houses));
vector<int> prefix(houses.size() + 1);
for (int i = 0; i < houses.size(); ++i) {
prefix[i + 1] = prefix[i] + houses[i];
}
vector<int> dp(houses.size());
for (int j = 0; j < houses.size(); ++j) {
dp[j] = cost(prefix, 0, j);
}
for (int m = 1; m < k; ++m) {
for (int j = houses.size() - 1; j >= 0; --j) {
for (int i = m; i <= j; ++i) {
dp[j] = min(dp[j], dp[i - 1] + cost(prefix, i, j));
}
}
}
return dp.back();
}
private:
int cost(const vector<int>& prefix, int i, int j) {
return (prefix[j + 1] - prefix[(i + j + 1) / 2]) -
(prefix[(i + j) / 2 + 1] - prefix[i]);
}
};