【JAVA算法题】职业抢劫

题目

/*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. 
 * */
/*你是一个职业抢劫犯,打算沿着街道抢劫房子。
 * 每个房子都有一定量的存款,唯一的约束阻止你抢它们是相邻的房屋有安全系统连接,
 * 它会自动与警方联系,如果两个相邻的房屋被分解成在同一个晚上。
 * 给出一个代表每个房子的钱的非负整数的列表,确定今晚你能抢劫的最大金额而不必报警。
 * */

 

代码

动态规划法(重点)

 1 //动态规划
 2 import java.util.*;
 3 public class Main {
 4     public static void main(String[] args) {
 5         Scanner sc = new Scanner(System.in);
 6         int a = sc.nextInt();
 7         int aa[] = new int[a];
 8         for(int i=0;i<aa.length;i++){
 9             aa[i] = sc.nextInt();
10         }
11         if(aa.length==1){
12             System.out.println(aa[0]);
13             return;
14         }
15         if(aa.length==2){
16             System.out.println(Math.max(aa[0],aa[1]));
17             return;
18         }
19         aa[2] += aa[0];
20         if(aa.length==3){
21             System.out.println(Math.max(aa[2], aa[3]));
22             return;
23         }
24         for(int i=3;i<aa.length;i++){
25             aa[i] += Math.max(aa[i-2], aa[i-3]);
26         }
27         System.out.println(Math.max(aa[aa.length-1], aa[aa.length-2]));
28     }
29 }

 

解析

  最优解的问题一般都可以用动态规划算法

 动态规划算法: 
1.全局最优解中一定包含某个局部最优解,但不一定包含前一个局部最优解,因此需要记录之前的所有最优解 
2.动态规划的关键是状态转移方程,即如何由以求出的局部最优解来推导全局最优解 
3.边界条件:即最简单的,可以直接得出的局部最优解

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

因为相邻的两个不能一起计算,所以最后还要比较最后一个和倒数第二个的大小以求出最优解

 

posted @ 2017-02-18 16:16  Luking  阅读(562)  评论(0编辑  收藏  举报