代码随想录 213.打家劫舍Ⅱ

思路:这道题是在198.打家劫舍的基础上,出现了环。对于一个数组,成环的条件主要有如下三种情况。

1.考虑不包含首尾元素:

2.考虑包含首元素,不包含尾元素:

3.考虑包含尾元素,不包含首元素:

4.注意:

(1)这里只是考虑。以情况3为例,虽然是考虑包含尾元素,但不一定要选尾元素。对于情况3,取nums[1]和nums[3]就是最大的。

(2)情况2和情况3都包含情况1了,所以只考虑情况2和情况3就可以了。

附代码:

java 复制代码
class Solution {
    public int rob(int[] nums) {
        if(nums == null || nums.length == 0){
            return 0;
        }
        int len = nums.length;
        if(len == 1){
            return nums[0];
        }
        return Math.max(robAction(nums,0,len - 1),robAction(nums,1,len));
    }

    int robAction(int[] nums,int start,int end){
        int[] res = new int[3];
        for(int i = start;i < end;i++){
            res[2] = Math.max(res[0] + nums[i],res[1]);
            res[0] = res[1];
            res[1] = res[2];
        }
        return res[2];
    }
}
相关推荐
lg_cool_21 小时前
Python 框架之py_trees
开发语言·数据结构·python
曹牧21 小时前
svn: svn relocate ‌之externals‌
数据结构·svn
北顾笙9801 天前
day20-数据结构力扣
数据结构·算法·leetcode
深邃-1 天前
【C语言】-数据在内存中的存储(2):浮点数在内存中的存储
c语言·开发语言·数据结构·c++·算法·html5
洛水水1 天前
跳表(Skip List):思想、优劣与应用场景完全解读
数据结构·跳表
会编程的土豆1 天前
【数据结构与算法】堆排序底层原理
数据结构·c++·算法
Allen_LVyingbo1 天前
量子计算Dirac Notation基本教学—从零基础到读懂量子信息论文(上)
开发语言·数据结构·架构·健康医疗·量子计算
历程里程碑1 天前
Protobuf vs JSON vs XML:小白该怎么选?
xml·大数据·数据结构·elasticsearch·链表·搜索引擎·json
半瓶榴莲奶^_^1 天前
树--数据结构
数据结构
小肝一下1 天前
每日两道力扣,day7
数据结构·c++·算法·leetcode·双指针·hot100·接雨水,四数之和