Created
March 30, 2023 15:35
Leetcode Problem 198 - House Robber
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public int rob(int[] nums) { | |
int n = nums.length; | |
int[] dp = new int[n+1]; | |
Arrays.fill(dp,-1); | |
return rec(n-1, nums, dp); | |
} | |
private int rec(int i, int[] nums, int[] dp) { | |
if(i == 0) return nums[i]; | |
if(i<0) return 0; | |
if(dp[i] != -1) return dp[i]; | |
int pick = nums[i] + rec(i-2, nums, dp); | |
int nonPick = rec(i-1, nums, dp); | |
return dp[i] = Math.max(pick,nonPick); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment