当前位置:网站首页>LeetCode 213. Robbery II (2022.08.01)
LeetCode 213. Robbery II (2022.08.01)
2022-08-02 02:00: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));
}
};
边栏推荐
猜你喜欢
随机推荐
Hiring a WordPress Developer: 4 Practical Ways
pcie inbound和outbound关系
Analysis of volatile principle
MySQL——增删查改操作
PHP直播源码实现简单弹幕效果的相关代码
Redis 持久化 - RDB 与 AOF
Kubernetes之本地存储
Redis 订阅与 Redis Stream
雇用WordPress开发人员:4个实用的方法
typescript32-ts中的typeof
用位运算为你的程序加速
【刷题篇】打家劫舍
A full set of common interview questions for software testing functional testing [open thinking questions] interview summary 4-3
Entry name ‘org/apache/commons/codec/language/bm/gen_approx_greeklatin.txt’ collided
【LeetCode每日一题】——103.二叉树的锯齿形层序遍历
【LeetCode每日一题】——654.最大二叉树
飞桨开源社区季度报告来啦,你想知道的都在这里
『网易实习』周记(二)
LeetCode刷题日记:74. 搜索二维矩阵
The ultra-large-scale industrial practical semantic segmentation dataset PSSL and pre-training model are open source!









