diff --git a/CoinChange.java b/CoinChange.java new file mode 100644 index 00000000..fddb7a7e --- /dev/null +++ b/CoinChange.java @@ -0,0 +1,31 @@ +// Time Complexity : O(amount * n) where n is number of coins +// Space Complexity : O(amount * n) where n is number of coins +// Did this code successfully run on Leetcode : No, time exceeded +// Any problem you faced while coding this : + +// Your code here along with comments explaining your approach +//Bruce force - recursive solution +class Solution { + public int coinChange(int[] coins, int amount) { + int res= helper(coins, amount, 0); + if (res>=Integer.MAX_VALUE-10) { + return -1; + } + return res; + } + private int helper(int[] coins, int amount, int idx){ + //base + if (amount ==0 ) return 0; + if (idx== coins.length || amount <0 ) return Integer.MAX_VALUE - 10; + // just so it infinity wont overflow when we add the coins addition. + + //logic + // did not choose + int case1 = helper (coins, amount, idx +1); + // choose + int case2 =1 + helper(coins, amount- coins[idx], idx); + int res= Math.min(case1, case2); + return res; + + } +} \ No newline at end of file diff --git a/Sample.java b/Sample.java index 1739a9cb..3c06ba5c 100644 --- a/Sample.java +++ b/Sample.java @@ -1,7 +1,30 @@ -// Time Complexity : -// Space Complexity : -// Did this code successfully run on Leetcode : -// Any problem you faced while coding this : - +// Time Complexity :O(n) +// Space Complexity : O(1) +// Did this code successfully run on Leetcode : Yes +// Any problem you faced while coding this : // Your code here along with comments explaining your approach +/* +At every house, you have 2 choices, either rob it or skip it. + 1. Skip the current house → keep previous maximum. + 2. Rob the current house → add its money to the best value from two houses back. +*/ + +class Solution { + public int rob(int[] nums) { + int n = nums.length; + //base + if (n==0) return 0; + if (n==1) return nums[0]; + + int[] dp = new int[n]; + int prev=nums[0]; + int curr= Math.max(nums[0], nums[1]); + for (int i = 2; i