-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweek 5 265. Paint House II
42 lines (37 loc) · 1.01 KB
/
week 5 265. Paint House II
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
37
38
39
40
41
42
public class Solution {
public int minCostII(int[][] costs) {
if(costs == null || costs.length == 0 || costs[0].length == 0) {
return 0;
}
int n = costs.length;
int k = costs[0].length;
if(k == 1){
return (n==1? costs[0][0] : -1);
}
int prevMin = 0;
int prevMinInd = -1;
int prevSecMin = 0;
for(int i = 0; i<n; i++) {
int min = Integer.MAX_VALUE;
int minInd = -1;
int secMin = Integer.MAX_VALUE;
for(int j = 0; j<k; j++) {
int val = costs[i][j] + (j == prevMinInd ? prevSecMin : prevMin);
if(minInd < 0) {
min = val;
minInd = j;
}else if(val < min) {
secMin = min;
min = val;
minInd = j;
} else if(val < secMin) {
secMin = val;
}
}
prevMin = min;
prevMinInd = minInd;
prevSecMin = secMin;
}
return prevMin;
}
}