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
67 changes: 67 additions & 0 deletions CoinChange.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// Time Complexity : O(N)
// Space Complexity : O(N)
// Did this code successfully run on Leetcode : yes
// Any problem you faced while coding this :


// Your code here along with comments explaining your approach
class Solution {
public int coinChange(int[] coins, int amount) {
// 2D DP
// // 0 to coins is row
// // 0 to amount is col
// int[][] dp = new int[coins.length+1][amount+1];
// // set first row (coin 0) to max value - coz we are considering min
// // we can consider amount+1 as max value
// for(int i = 1; i <= amount; i++)
// {
// dp[0][i] = amount+1;
// }

// for(int i = 1; i <= coins.length; i++)
// {
// for(int j = 0; j <= amount; j++)
// {
// if(coins[i-1] > j)
// {
// // as value as the grid above
// dp[i][j] = dp[i-1][j];
// }
// else
// {
// dp[i][j] = Math.min(dp[i-1][j], 1+ dp[i][j - coins[i-1]]);
// }
// }
// }

// if(dp[coins.length][amount] >= amount + 1)
// {
// return -1;
// }
// return dp[coins.length][amount];

// 1D DP
int dp[] = new int[amount+1];
for(int i = 1; i <= amount; i++)
{
dp[i] = amount+1;
}
for(int i = 1; i <= coins.length; i++)
{
for(int j = 0; j <= amount; j++)
{
if(coins[i - 1] > j)
{
dp[j] = dp[j];
}
else
{
dp[j] = Math.min(dp[j], dp[j- coins[i-1]] + 1);
}
}
}
if(dp[amount] >= amount+1) return -1;
return dp[amount];
}
}

37 changes: 37 additions & 0 deletions HouseRobber.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// Time Complexity : O(N)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode :
// Any problem you faced while coding this :


// Your code here along with comments explaining your approach

class Solution {
public int rob(int[] nums) {
// 1D array
// if(nums.length == 1) return nums[0];

// int dp[] = new int[nums.length];
// dp[0] = nums[0];
// dp[1] = Math.max(nums[0], nums[1]);
// for(int i = 2; i < nums.length; i++)
// {
// dp[i] = Math.max(nums[i] + dp[i-2], dp[i-1]);
// }
// return dp[nums.length - 1];

// two variables
if(nums.length == 1) return nums[0];
int prev = nums[0];
int curr = Math.max(nums[0], nums[1]);

for(int i = 2; i < nums.length; i++)
{
int temp = Math.max(curr, prev+nums[i]);
prev = curr;
curr = temp;
}

return curr;
}
}