Simple repeat the house robber I


  • 0
    H

    public class Solution {
    public int rob(int[] nums) {
    if(nums.length==0) 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 + 1][2];
    int[][] dp2 = new int[nums.length + 1][2];
    int[][] dp3 = new int[nums.length + 1][2];int max=0;
    for (int i = 1; i <= nums.length-1; i++) {
    dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1]);
    dp[i][1] = nums[i - 1] + dp[i - 1][0];
    }
    int max1= Math.max(dp[nums.length-1][0], dp[nums.length-1][1]);
    for (int i = 2; i <= nums.length; i++) {
    dp2[i][0] = Math.max(dp2[i - 1][0], dp2[i - 1][1]);
    dp2[i][1] = nums[i - 1] + dp2[i - 1][0];
    }
    int max2= Math.max(dp2[nums.length][0], dp2[nums.length][1]);max=Math.max(max1,max2);
    for (int i = 2; i <= nums.length-1; i++) {
    dp3[i][0] = Math.max(dp3[i - 1][0], dp3[i - 1][1]);
    dp3[i][1] = nums[i - 1] + dp3[i - 1][0];
    }
    int max3= Math.max(dp3[nums.length-1][0], dp3[nums.length-1][1]);
    max=Math.max(max,max3);
    return max;
    }
    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.