码迷,mamicode.com
首页 > 其他好文 > 详细

House Robber 解答

时间:2015-09-20 00:06:25      阅读:415      评论:0      收藏:0      [点我收藏+]

标签:

Question

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.

Solution 1 -- DP

The key is to find the relation dp[i] = Math.max(dp[i-1], dp[i-2]+num[i-1]). Time complexity O(n), space cost O(n).

 1 public class Solution {
 2     public int rob(int[] nums) {
 3         if (nums == null || nums.length < 1)
 4             return 0;
 5         int length = nums.length;
 6         int[] dp = new int[length + 1];
 7         dp[0] = 0;
 8         dp[1] = nums[0];
 9         for (int i = 2; i <= length; i++) {
10             dp[i] = Math.max(dp[i - 1], nums[i - 1] + dp[i - 2]);
11         }
12         return dp[length];
13     }
14 }

Solution 2

Another method is to use two counters, one for even number and the other for odd number.

 1 public class Solution {
 2     public int rob(int[] nums) {
 3         if (nums == null || nums.length < 1)
 4             return 0;
 5         int odd = 0, even = 0, length = nums.length;
 6         for (int i = 0; i < length; i++) {
 7             if (i % 2 == 0) {
 8                 even += nums[i];
 9                 even = even > odd ? even : odd;
10             } else {
11                 odd += nums[i];
12                 odd = odd > even ? odd : even;
13             }
14         }
15         return even > odd ? even : odd;
16     }
17 }

 

House Robber 解答

标签:

原文地址:http://www.cnblogs.com/ireneyanglan/p/4822508.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!