|
| 1 | +""" |
| 2 | +Code for house robber problem LeetCode : 198 using dynamic programming (tabulation). |
| 3 | +""" |
| 4 | + |
| 5 | +### Question explanation: |
| 6 | +# Given array of numbers which says how much money you can steel form houses. |
| 7 | +# The only constraint is if you rob from adjacent houses, it will ring alarm to police. |
| 8 | + |
| 9 | +### My Approach with DP: |
| 10 | +# As starting with DP, I will explain the approach in recursion with memoization which is more intuitive. |
| 11 | +# At each node in recursion, we have counter which True or False |
| 12 | +# Starting from last house, we have 2 options 1) If choosen, counter=True will be passed in recursion. |
| 13 | +# 2) If not choosen, counter=False will be passes in recursion. |
| 14 | +# If choosen=True at current house means previous house is choose so you can't choose current house. |
| 15 | +# If choosen=False at current house means it is not choosen, it means you have option to choose or not current house. |
| 16 | +## Example nums=[1,2,3,1] |
| 17 | + |
| 18 | +### Last index value (1, counter=False) (as we are starting from here we are free to choose) |
| 19 | +# / \ |
| 20 | +### (3,counter=True) (3,counter=False) (counter=True mean 1 is choosen,so avoid 3) |
| 21 | +# / / \ |
| 22 | +### (2,counter=False) (2,True) (2,False) |
| 23 | +# (here 2,False means 1 is choosen, so we avoid 3 and |
| 24 | +# as 3 is avoided now again we are free to choose at house 2) |
| 25 | + |
| 26 | + |
| 27 | +## Note: dp[i][0]=>0 is True and 1 is False in convention. |
| 28 | +def rob(nums): |
| 29 | + def helper(nums,dp,i,j): |
| 30 | + if i<0: |
| 31 | + return 0 |
| 32 | + if dp[i][j]!=-1: |
| 33 | + return dp[i][j] |
| 34 | + if j==True: |
| 35 | + dp[i][0]=helper(nums,dp,i-1,False) |
| 36 | + return dp[i][0] |
| 37 | + else: |
| 38 | + dp[i][1] = max(nums[i] + helper(nums,dp,i-1,True), helper(nums,dp,i-1,False)) |
| 39 | + return dp[i][1] |
| 40 | + dp=[[-1]*2 for _ in range(0,len(nums))] |
| 41 | + return helper(nums,dp,len(nums)-1,False) |
| 42 | + |
| 43 | +if __name__ == "__main__": |
| 44 | + nums=[2,7,9,3,1] |
| 45 | + if not nums: |
| 46 | + print('The list is empty') |
| 47 | + else: |
| 48 | + max_amount=rob(nums) |
| 49 | + print(max_amount) |
| 50 | + |
| 51 | + |
| 52 | + |
0 commit comments