Advertisement
imashutosh51

Paint house

Aug 8th, 2022
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.12 KB | None | 0 0
  1. /*
  2. Logic:
  3. dp array rows represents houses and 3 columns for red,blue and green colors.
  4. dp[i][j] will store the minimum cost by coloring ith house by jth color ie. j=0->red,j=1->blue,j=2->green
  5. coloring of first house with jth colors will be costs[0][j]
  6. so,if we color ith house with red,then minimum cost till ith house will be min of cost of previous house
  7. colored with blue and green because same color can't be in adjacent house and same goes for other colors also.
  8. finally,in last row,we will have minimum cost coloring last house with red,blue and green,return their minimum.
  9. */
  10.  
  11. int Solution::solve(vector<vector<int> > &costs) {
  12.         int n=costs.size();
  13.         vector<vector<int> > dp(n, vector<int>(3, 0));
  14.         dp[0][0]=costs[0][0];
  15.         dp[0][1]=costs[0][1];
  16.         dp[0][2]=costs[0][2];
  17.         for(int i=1;i<costs.size();i++){
  18.             dp[i][0]=min(dp[i-1][1],dp[i-1][2])+costs[i][0];
  19.             dp[i][1]=min(dp[i-1][0],dp[i-1][2])+costs[i][1];
  20.             dp[i][2]=min(dp[i-1][0],dp[i-1][1])+costs[i][2];
  21.         }
  22.         n--;
  23.         return min(min(dp[n][0],dp[n][1]),dp[n][2]);        
  24. }
  25.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement