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.spa

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.code

一維DP便可。blog

 1 public class Solution {
 2     public int rob(int[] num) {
 3         if(num == null || num.length == 0) return 0;
 4         int len = num.length;
 5         int[] dp = new int[len + 1];
 6         dp[1] = num[0];
 7         for(int i = 2; i <= len; i ++){
 8             dp[i] = Math.max(dp[i - 1], dp[i - 2] + num[i - 1]);
 9         }
10         return dp[len];
11     }
12 }
相關文章
相關標籤/搜索