[LeetCode] House Robber II
This problem is a little tricky at first glance. However, if you have finished the House Robber problem, 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
- Rob houses
0
ton - 2
; - Rob houses
1
ton - 1
.
The code is as follows (some edge cases are handled explicitly).
1 int robHelper(vector<int>& nums, int left, int right){ 2 if (left == right) return nums[left]; 3 vector<int> money(right - left + 1, 0); 4 money[0] = nums[left]; 5 money[1] = max(nums[left], nums[left + 1]); 6 for (int i = 2; i <= right - left; i++) 7 money[i] = max(money[i - 1], money[i - 2] + nums[left + i]); 8 return money[money.size() - 1]; 9 } 10 int rob(vector<int>& nums) { 11 if (nums.empty()) return 0; 12 int n = nums.size(); 13 if (n == 1) return nums[0]; 14 return max(robHelper(nums, 0, n - 2), robHelper(nums, 1, n - 1)); 15 }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 从零开始开发一个 MCP Server!
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· .NET 原生驾驭 AI 新基建实战系列(一):向量数据库的应用与畅想
· Ai满嘴顺口溜,想考研?浪费我几个小时
· Browser-use 详细介绍&使用文档