Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions CoinChange.java
Original file line number Diff line number Diff line change
@@ -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;

}
}
33 changes: 28 additions & 5 deletions Sample.java
Original file line number Diff line number Diff line change
@@ -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<n; i++){
int temp = curr;
curr= Math.max(curr, nums[i] + prev);
prev=temp;
}
return curr;
}
}