[LeetCode] House Robber II

This problem is a little tricky at first glance. However, if you have finished the House Robberproblem, this problem can simply be decomposed into two House Robber problems. Suppose there are n houses, since house 0 and n - 1 are now neighbors, we cannot rob them together and thus the solution is now the maximum of

  1. Rob houses 0 to n - 2;
  2. Rob houses 1 to n - 1.

The code is as follows. Some edge cases (n <= 2) are handled explicitly.

复制代码
 1 class Solution {
 2 public:
 3     int rob(vector<int>& nums) {
 4         int n = nums.size();
 5         if (n <= 2) return n ? (n == 1 ? nums[0] : max(nums[0], nums[1])) : 0;
 6         return max(robber(nums, 0, n - 2), robber(nums, 1, n -1));
 7     }
 8 private:
 9     int robber(vector<int>& nums, int l, int r) {
10         int pre = 0, cur = 0;
11         for (int i = l; i <= r; i++) {
12             int temp = max(pre + nums[i], cur);
13             pre = cur;
14             cur = temp;
15         } 
16         return cur;
17     }
18 };
复制代码

 

posted @   jianchao-li  阅读(208)  评论(0编辑  收藏  举报
编辑推荐:
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
阅读排行:
· 从零开始开发一个 MCP Server!
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· .NET 原生驾驭 AI 新基建实战系列(一):向量数据库的应用与畅想
· Ai满嘴顺口溜,想考研?浪费我几个小时
· Browser-use 详细介绍&使用文档
点击右上角即可分享
微信分享提示