diff --git a/Problem1.java b/Problem1.java new file mode 100644 index 00000000..4efde39e --- /dev/null +++ b/Problem1.java @@ -0,0 +1,42 @@ +// Time Complexity : O(N) ~ where N is the number of houses to be colored +// Space Complexity : O(1) +// Did this code successfully run on Leetcode : Yes +// Any problem you faced while coding this : No + + +// Your code here along with comments explaining your approach +/* +Initially took a 1-D array of 3 size where initialzed with the first row of costs. +Then in each iteration added the current row,col value + the minimum of previous row. Eg - if 0, then previous row 1 and 2 columns. +Held the previous row red and blue in temp variables since the value will be updated in each iteration +*/ + + +public class Problem1 { + public int minCost(int[][] costs) { + if(costs.length == 0) { + return 0; + } + + int m = costs.length; + int[] dp = new int[3]; + + dp[0] = costs[0][0]; + dp[1] = costs[0][1]; + dp[2] = costs[0][2]; + for(int i = 1;i j) { + dp[i][j] = dp[i-1][j]; + } else { + dp[i][j] = dp[i-1][j] + dp[i][j - coins[i-1]]; + } + } + } + return dp[m][n]; + } +}