LeetCode House Robber II

来源:互联网 发布:history linux 编辑:程序博客网 时间:2024/06/05 04:04

原题链接在这里:https://leetcode.com/problems/house-robber-ii/

House Robber的进阶题。这里第一家和最后一家不能同时偷,所以像House Robber建立一个res1, 把从第一家到倒数第二家能偷最大值依次存入res1, 再建立一个res2, 把第二家到最后一家能偷最大值依次存入res2. 返回res1最后一个值 和res2最后一个值中较大者。

Note: 1. 不要忘记initialize res1[0],res1[1].

2. res2赋值时,用的是nums[i+1] , res1赋值时,用的是nums[i].

AC Java:

public class Solution {    public int rob(int[] nums) {        if(nums == null || nums.length == 0){            return 0;        }        if(nums.length == 1){            return nums[0];        }        if(nums.length == 2){            return Math.max(nums[0],nums[1]);        }                int[] res1 = new int[nums.length-1];        res1[0] = nums[0];        res1[1] = Math.max(nums[0],nums[1]);        for(int i = 2; i < res1.length; i++){            res1[i] = Math.max(res1[i-2]+nums[i], res1[i-1]);        }                int[] res2 = new int[nums.length-1];        res2[0] = nums[1];        res2[1] = Math.max(nums[1],nums[2]);        for(int i = 2; i < res2.length; i++){            res2[i] = Math.max(res2[i-2]+nums[i+1],res2[i-1]);         }        return Math.max(res1[nums.length-2], res2[nums.length-2]);    }}


0 0