LeetCode | HouseCode 算法题

题目:

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.

题目大意:

你是一名专业强盗,计划沿着一条街打劫。每间房屋都储存有一定金额的钱,唯一能阻止你打劫的约束条件就是房屋之间有安全系统相连,如果同一个晚上有两间相邻的房屋被闯入,它们就会自动联络警察,因此不可以打劫相邻的房屋。 重点内容给定一列非整,代表每间房屋的金额,算出在不惊动警察的前提下一晚上最多可以打劫到的金钱数。

解题思路:动态规划(Dynamic Programming)

用状态转移方程:sum[i] += Math.max(sum[i-2], sum[i-3]);

第i个位置的最大值由max(sum[i-2], sum[i-3])决定, 把最大值转移给sum[i]

 

算法源码:

 1 package HouseRobber;
 2 public class Main {
 3     public static void main(String[] args){
 4         int[] sum= {1,9,10,10,7};
 5         System.out.println(robber(sum));
 6     }
 7     public static int robber(int[] sum){
 8         if (sum== null || sum.length == 0) {
 9             return 0;
10         }
11         //如果只有一个元素,返回这个元素值
12         if(sum.length==1){
13             return sum[0];
14         }
15         else if(sum.length==2){    
16         //如果有两个元素,返回其中较大的值
17             return Math.max(sum[0], sum[1]);
18         }else if(sum.length==3){    
19         //如果有三个元素,比较第一个元素和第三个元素之和与第二个元素的值,返回较大者
20             return Math.max(sum[0]+sum[2], sum[1]);
21         }
22         //把第一个和第三个元素的和赋给第三个元素,以便以后比较
23         if (sum.length > 3) {
24             sum[2] += sum[0];
25         }
26         //从第四个元素开始处理就需要用到公式了,也是从第四个开始重新赋值,元素少于四的时候,公式不成立
27         int i = 3;
28         for(;i<sum.length;i++){
29              sum[i] += Math.max(sum[i-2], sum[i-3]);
30         }
31         //举个例子:如有4个元素,i=3,执行一次循环之后(这个时候i=4):最后一个元素=最后一个元素+前两个中较大的;
32         return Math.max(sum[i-1], sum[i-2]);//再比较最后一个和倒数第二个 
33     }
34 }

 原文链接:http://blog.csdn.net/promiseyufei/article/details/55657580

posted @ 2017-02-18 17:20  万变不离许嵩  阅读(498)  评论(0编辑  收藏  举报