Leetcode - 198. House Robber
URL : https://leetcode.com/problems/house-robber/
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
Example 1:
Input: [1,2,3,1] Output: 4 Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4.
Example 2:
Input: [2,7,9,3,1] Output: 12 Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). Total amount you can rob = 2 + 9 + 1 = 12.
解决方案
/** * 罗列出每天偷Y和不偷N的盈利情况 * Y(n) = nums[n] + N(n-1); //前一天肯定不能偷,再加上今天偷的金额 * N(n) = Max(Y(n-1), N(n-1)); //前一天偷或者不偷均可,选取最大值。因为今天不再偷,所以不必加另外的金额 * 最后的结果就是Max(Y(n),N(n))... */ import java.lang.Math; class Solution { public int rob(int[] nums) { if(nums == null || nums.length < 1){ return 0; } int pre_yes = 0; int pre_no = 0; int cur_yes = 0; int cur_no = 0; for(int i = 0; i < nums.length; ++i){ cur_yes = nums[i] + pre_no; cur_no = Math.max(pre_yes,pre_no); pre_yes = cur_yes; pre_no = cur_no; } return Math.max(pre_yes,pre_no); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?