LeetCode 198. House Robber

原题连接在这里:https://leetcode.com/problems/house-robber/html

题目:post

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 url

题解:spa

DP问题. state 到当前house能偷到的最多钱. 转移方程 dp[i] = Math.max(dp[i-1], dp[i-2]+nums[i-1]). code

优化空间. 只用维护前面两个值就够.htm

Time Complexity: O(n). Space: O(1).blog

AC Java:leetcode

 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 IIHouse Robber III.get

相似Paint HouseMaximum Product SubarrayDelete and Earn.

相关文章
相关标签/搜索