Java simple solution


  • -2
    W
    public class Solution {
    public int rob(int[] nums) {                 //就是nums[0] num[n-1]不能同时取,那么不取nums[0]得到一个结果
                                                                //不取nums[n-1]得到一个结果,两个结果看哪个好,当然也包括两个
                                                               //两个都不取
        int max = 0;
        if(nums.length == 0){
            return max;
        }
        if(nums.length == 1){
            return nums[0];
        }
        if(nums.length == 2){
            return Math.max(nums[0], nums[1]);
        }
        int[] dp1 = new int[nums.length];
        int[] dp2 = new int[nums.length];
        int i = 0;
        int j = 1;
        for(; i <= nums.length -2 && j <= nums.length -1; i++, j++){//分为两种情况,抢第一个,或者抢最后一个
                                                                    //其实再次细分,当0参与,分为抢0, 不抢0,但是永远不抢n-1
                                                                    //当n-1参与,分为抢n-1,不抢n-1,但是永远不抢0;
                                                                    //所以最后的结果最大值的结果,不抢0,获得一个,不抢n-1或者一个,
                                                                    
            if(i == 0 && j == 1){
                dp1[i] = nums[i];
                dp2[j] = nums[j];
            }
            else if( i == 1 && j == 2){
                dp1[i] = Math.max(dp1[i-1], nums[i]);
                dp2[j] = Math.max(dp2[j-1], nums[j]);
            }
            else{
                dp1[i] = Math.max(dp1[i-1], nums[i] + dp1[i-2]);
                dp2[j] = Math.max(dp2[j-1], nums[j] + dp2[j-2]);
            }
        }
        max = Math.max(dp1[nums.length-2], dp2[nums.length-1]);
        return max;
    }
    

    }


Log in to reply
 

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