Advertisement
AC_is_here

Paint Houses 2

Oct 25th, 2021
983
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.97 KB | None | 0 0
  1. public int minCostII(int[][] costs) {
  2.         // write your code here
  3.         if(costs.length==0) return 0;
  4.         else{
  5.             int[][] dp = new int[costs.length][costs[0].length];
  6.             for(int i=0;i<dp[0].length;i++)
  7.                 dp[0][i] = costs[0][i];
  8.             for(int i=1;i<dp.length;i++){
  9.                 for(int j=0;j<dp[0].length;j++){
  10.                     dp[i][j] = costs[i][j]+findMinCost(dp[i-1],j);
  11.                 }
  12.             }
  13.             int ans = dp[dp.length-1][0];
  14.             for(int i=1;i<dp[0].length;i++){
  15.                 if(dp[dp.length-1][i]<ans)
  16.                     ans = dp[dp.length-1][i];
  17.             }
  18.             return ans;
  19.         }
  20.     }
  21.  
  22.     private int findMinCost(int[] row,int choice){
  23.         int min = Integer.MAX_VALUE;
  24.         for(int i=0;i<row.length;i++){
  25.             if(i!=choice){
  26.                 if(row[i]<min)
  27.                     min = row[i];
  28.             }
  29.         }
  30.         return min;
  31.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement