From 2ada485f46a3bde584363a6904108b7824f33f7b Mon Sep 17 00:00:00 2001 From: pranshugoyal0111 <46605937+pranshugoyal0111@users.noreply.github.com> Date: Wed, 7 Aug 2019 00:19:49 -0700 Subject: [PATCH 1/2] Create Problem --- Problem | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 Problem diff --git a/Problem b/Problem new file mode 100644 index 00000000..3cffd6bd --- /dev/null +++ b/Problem @@ -0,0 +1,10 @@ +I currently have difficulty in coding out dp problems. Will update the code after the class +Howvever for the coin change problem , I have an approach in mind that I think should work. + +There are 2 cases for each coin. Either that coin will be included in the sum that we have to achieve or that coin will not be included. + +coin(amount , n) -> let this denote the amount that can be achieved using n coins. + = coin(amount- j, n) + 1 if ith coin with value j is included + or coin(amount, n-1) if ith coin is not included + + From 52cc0c1b68738a6fc3439a739aca6aaee062235f Mon Sep 17 00:00:00 2001 From: pranshugoyal0111 <46605937+pranshugoyal0111@users.noreply.github.com> Date: Wed, 7 Aug 2019 20:49:37 -0700 Subject: [PATCH 2/2] Create Robber.java --- Robber.java | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Robber.java diff --git a/Robber.java b/Robber.java new file mode 100644 index 00000000..5e260991 --- /dev/null +++ b/Robber.java @@ -0,0 +1,40 @@ +// Time Complexity : O(n) +// Space Complexity : O(n) +// Did this code successfully run on Leetcode :yes +// Any problem you faced while coding this : took help from geeksforgeeks + +// First 3 cases handle the scenarios when we have 0 or 1 or 2 houses +// Then for more than 3 houses, at every house we have to take a decision to rob that house or not. We take this decision +// by calculating maximum of ( money robbed till 2 houses before that plus money in that house or money robbed till one house +// before it) + + +class Solution { + public int rob(int[] nums) { + + if(nums.length==0 || nums==null) + return 0; + + if(nums.length==1) + return nums[0]; + + if(nums.length==2) + return Math.max(nums[0],nums[1]); + + + int[] dp = new int[nums.length]; + + //Base Case + 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]; + + } +}