上善若水 大盈若冲
LeetCode link
solution
12345678910111213141516171819202122232425
class Solution { public int rob(int[] nums) { if (nums == null || nums.length < 1) { return 0; } int n = nums.length; if (n == 1) { return nums[0]; } int[][] dp = new int[n][n]; for (int i = 0; i < n; i++) { dp[i][i] = nums[i]; } for (int i = 0; i < n - 1; i++) { dp[i][i + 1] = Math.max(dp[i][i], dp[i + 1][i + 1]); } for (int k = 2; k < n; k++) { for (int i = 0; i + k < n; i++) { int j = i + k; dp[i][j] = Math.max(dp[i][j - 1], dp[i][j - 2] + nums[j]); } } return dp[0][n - 1]; }}
promote
There’s no need to build a 2d-array, 1d is enough.
123456789101112131415161718
class Solution { public int rob(int[] nums) { if (nums == null || nums.length < 1) { return 0; } int n = nums.length; if (n == 1) { return nums[0]; } int[] dp = new int[n]; dp[0] = nums[0]; dp[1] = Math.max(nums[0], nums[1]); for (int i = 2; i < n; i++) { dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i]); } return dp[n - 1]; }}