-
Notifications
You must be signed in to change notification settings - Fork 1
/
Allocate Mailboxes
36 lines (34 loc) · 1.28 KB
/
Allocate Mailboxes
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
32
33
34
35
36
class Solution {
public int minDistance(int[] houses, int k) {
Arrays.sort(houses);
if(k >= houses.length) return 0;
int[][] dp = new int[houses.length][k+1];
for(int i = 0; i<dp.length; i++){
Arrays.fill(dp[i], 100000000);
}
for(int i = houses.length-1; i>=0; i--){
for(int j = k; j>=1; j--){
if(j >= (houses.length-i)){
dp[i][j] = 0;
}
else{
int sum = 0;
int minDist = Integer.MAX_VALUE;
boolean add = false;
for(int l = i, z = i; l<=(houses.length-j); l++){
//System.out.println("hi");
sum += (houses[l] - houses[z]);
//System.out.println((l+1<houses.length ? dp[l+1][j-1] : 0));
minDist = Math.min(minDist, sum + (l+1<houses.length ? dp[l+1][j-1] : 0));
if(add) z++;
add = !add;
}
//System.out.println(minDist);
dp[i][j] = minDist;
}
}
}
//System.out.println(Arrays.deepToString(dp));
return dp[0][k];
}
}