Created
June 14, 2020 19:22
-
-
Save shixiaoyu/c664335d2725f679ca89077908dcec48 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
public int rob(int[] nums) { | |
if (nums == null || nums.length == 0) { | |
return 0; | |
} | |
if (nums.length == 1) { | |
return nums[0]; | |
} | |
// rob first house, so need to remove the last house | |
int[] rob_first_nums = new int[nums.length - 1]; | |
for (int i = 0; i < rob_first_nums.length; i++) { | |
rob_first_nums[i] = nums[i]; | |
} | |
// do not rob first house, start from the 2nd and rob to the end of the house | |
int[] rob_no_first_nums = new int[nums.length - 1]; | |
for (int i = 1; i < nums.length; i++) { | |
rob_no_first_nums[i - 1] = nums[i]; | |
} | |
int rob_first_max = this.robFlatRow(rob_first_nums); | |
int rob_no_first_max = this.robFlatRow(rob_no_first_nums); | |
return Math.max(rob_first_max, rob_no_first_max); | |
} | |
public int robFlatRow(int[] num) { | |
if (num == null || num.length == 0) { | |
return 0; | |
} | |
int n = num.length; | |
int[] lookup = new int[n + 1]; // DP array size normally larger than 1 | |
lookup[0] = 0; | |
lookup[1] = num[0]; | |
for (int i = 2; i <= n; i++) { | |
lookup[i] = Math.max(lookup[i - 1], lookup[i - 2] + num[i - 1]); | |
} | |
return lookup[n]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment