From ff46687fef6730dd89ae89dcf0fe309b75f33b91 Mon Sep 17 00:00:00 2001 From: sainathek Date: Mon, 12 Jan 2026 02:49:00 -0500 Subject: [PATCH] done Dp-1 --- problem1.java | 32 ++++++++++++++++++++++++++++++++ problem2.java | 26 ++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 problem1.java create mode 100644 problem2.java diff --git a/problem1.java b/problem1.java new file mode 100644 index 00000000..f2b45ed5 --- /dev/null +++ b/problem1.java @@ -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]; + } +} diff --git a/problem2.java b/problem2.java new file mode 100644 index 00000000..0066fad2 --- /dev/null +++ b/problem2.java @@ -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; + } +}