LeetCode 198. House Robber
原题链接在这里: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
题解:
DP问题. state 到当前house能偷到的最多钱. 转移方程 dp[i] = Math.max(dp[i-1], dp[i-2]+nums[i-1]).
优化空间. 只用维护前面两个值就够.
Time Complexity: O(n). Space: O(1).
AC Java:
1 class Solution { 2 public int rob(int[] nums) { 3 if(nums == null || nums.length == 0){ 4 return 0; 5 } 6 7 int include = 0; 8 int exclude = 0; 9 for(int i = 0; i<nums.length; i++){ 10 int in = include; 11 int ex = exclude; 12 exclude = Math.max(in, ex); 13 include = ex + nums[i]; 14 } 15 16 return Math.max(include, exclude); 17 } 18 }
跟上House Robber II, House Robber III, The Number of Beautiful Subsets.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步