当前位置:网站首页>力扣(LeetCode)213. 打家劫舍 II(2022.08.01)
力扣(LeetCode)213. 打家劫舍 II(2022.08.01)
2022-08-02 01:54:00 【ChaoYue_miku】
你是一个专业的小偷,计划偷窃沿街的房屋,每间房内都藏有一定的现金。这个地方所有的房屋都 围成一圈 ,这意味着第一个房屋和最后一个房屋是紧挨着的。同时,相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警 。
给定一个代表每个房屋存放金额的非负整数数组,计算你 在不触动警报装置的情况下 ,今晚能够偷窃到的最高金额。
示例 1:
输入:nums = [2,3,2]
输出:3
解释:你不能先偷窃 1 号房屋(金额 = 2),然后偷窃 3 号房屋(金额 = 2), 因为他们是相邻的。
示例 2:
输入:nums = [1,2,3,1]
输出:4
解释:你可以先偷窃 1 号房屋(金额 = 1),然后偷窃 3 号房屋(金额 = 3)。
偷窃到的最高金额 = 1 + 3 = 4 。
示例 3:
输入:nums = [1,2,3]
输出:3
提示:
1 <= nums.length <= 100
0 <= nums[i] <= 1000
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/house-robber-ii
方法一:动态规划
C++提交内容:
class Solution {
public:
int robRange(vector<int>& nums, int start, int end) {
int first = nums[start], second = max(nums[start], nums[start + 1]);
for (int i = start + 2; i <= end; i++) {
int temp = second;
second = max(first + nums[i], second);
first = temp;
}
return second;
}
int rob(vector<int>& nums) {
int length = nums.size();
if (length == 1) {
return nums[0];
} else if (length == 2) {
return max(nums[0], nums[1]);
}
return max(robRange(nums, 0, length - 2), robRange(nums, 1, length - 1));
}
};
边栏推荐
猜你喜欢

Multi-Party Threshold Private Set Intersection with Sublinear Communication-2021: Interpretation

Yunhe Enmo: Let the value of the commercial database era continue to prosper in the openGauss ecosystem

typescript33 - high-level overview of typescript

Huawei's 5-year female test engineer resigns: what a painful realization...

Redis Subscription and Redis Stream

【ORB_SLAM2】void Frame::ComputeImageBounds(const cv::Mat &imLeft)

用位运算为你的程序加速

Redis 订阅与 Redis Stream

传统企业数字化转型需要经过几个阶段?

『网易实习』周记(二)
随机推荐
60种特征工程操作:使用自定义聚合函数【收藏】
乱七八糟的网站
R语言使用table1包绘制(生成)三线表、使用单变量分列构建三线表、编写自定义三线表结构(将因子变量细粒度化重新构建三线图)、自定义修改描述性统计参数输出自定义统计量
『网易实习』周记(一)
Typescript31 - any type
滴滴秋招提前批正式开始,现在投递免笔试
Constructor instance method inheritance of typescript38-class (implement)
Newton's theorem and related corollaries
Anti-oversold and high concurrent deduction scheme for e-commerce inventory system
A full set of common interview questions for software testing functional testing [open thinking questions] interview summary 4-3
Analysis of volatile principle
MySQL8 下载、启动、配置、验证
Image fusion based on weighted 】 and pyramid image fusion with matlab code
HSDC is related to Independent Spanning Tree
力扣 1161. 最大层内元素和
创新项目实战之智能跟随机器人原理与代码实现
Understand the big model in seconds | 3 steps to get AI to write a summary
Some insights from 5 years of automated testing experience: UI automation must overcome these 10 pits
Effects of Scraping and Aggregation
牛顿定理和相关推论