-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKelements.java
51 lines (41 loc) · 1.74 KB
/
Kelements.java
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
43
44
45
46
47
48
49
50
51
class Kekements {
public int helper(int idx, int[] houses, int[][] cost,int target, int prevColor,int neigh,Integer[][][] dp)
{
if(idx==houses.length || neigh>target)
{
if(neigh==target)
return 0;
return Integer.MAX_VALUE;
}
if(dp[idx][prevColor][neigh]!=null)
return dp[idx][prevColor][neigh];
int minCost = Integer.MAX_VALUE;
if(houses[idx]==0)
{
for(int j = 0;j<cost[idx].length;j++)
{
int minCostHere = Integer.MAX_VALUE;
if(j+1==prevColor) // Painting the house with the same colour as that of the previous one.
minCostHere = helper(idx+1,houses,cost,target,prevColor,neigh,dp);
else // Painting the house with a different color and incrementing the neighbour count.
minCostHere = helper(idx+1,houses,cost,target,j+1,neigh+1,dp);
if(minCostHere!=Integer.MAX_VALUE)
minCostHere+=cost[idx][j];
minCost = Math.min(minCostHere,minCost);
}
}
else
{
if(houses[idx]==prevColor)
minCost = helper(idx+1,houses,cost,target,prevColor,neigh,dp);
else
minCost = helper(idx+1,houses,cost,target,houses[idx],neigh+1,dp);
}
return dp[idx][prevColor][neigh] = minCost;
}
public int minCost(int[] houses, int[][] cost, int m, int n, int target) {
Integer[][][] dp = new Integer[m][n+1][target+1];
int ans = helper(0,houses,cost,target,0,0,dp);
return ans==Integer.MAX_VALUE?-1:ans;
}
}