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
32 changes: 32 additions & 0 deletions problem1.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Time Complexity : O(n * amount)
// Space Complexity : O(amount)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No, just needed to initialize dp array properly with max values.


// Your code here along with comments explaining your approach in three sentences only
// I use dynamic programming where dp[i] stores the minimum coins needed to make amount i.
// For each amount, I try every coin and update dp if using that coin gives a better result.
// In the end, if dp[amount] is still large, return -1 otherwise return dp[amount].

import java.util.*;

class Solution {
public int coinChange(int[] coins, int amount) {

int[] dp = new int[amount + 1];
Arrays.fill(dp, amount + 1);

dp[0] = 0;

for (int i = 1; i <= amount; i++) {
for (int c : coins) {
if (i - c >= 0) {
dp[i] = Math.min(dp[i], dp[i - c] + 1);
}
}
}

return dp[amount] > amount ? -1 : dp[amount];
}
}
26 changes: 26 additions & 0 deletions problem2.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Time Complexity : O(n)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No, just needed to track previous two states.


// Your code here along with comments explaining your approach in three sentences only
// At each house, we decide either to rob it and add value to dp[i-2] or skip it and take dp[i-1].
// I only keep two variables to represent previous two states instead of full dp array.
// This gives maximum money that can be robbed without taking adjacent houses.

class Solution {
public int rob(int[] nums) {

int prev2 = 0; // dp[i-2]
int prev1 = 0; // dp[i-1]

for (int n : nums) {
int curr = Math.max(prev1, prev2 + n);
prev2 = prev1;
prev1 = curr;
}

return prev1;
}
}