标签:
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.
题目大意
你是一个抢劫犯,要抢一条大街上所有house,每个house的钱是一定的,不能抢两个相连的house,这样会引起报警。
给你一个数组int num[]表示这条街上所有house里面的钱。你最多能抢多少
思路
可以用DP做。最后的结果result[i] 可能有两种可能,最后一家i没有被抢,result[i] = result[i - 2],最后一家被抢了,result[i] = result[i - 1]。取这两个中最大值,递推公式为
result[i] = max{result[i - 1], result[i - 2] + num[i]}
result[i]表示抢到第i家house抢到的钱
1 public class Solution { 2 public int rob(int[] num) { 3 if(num == null || num.length == 0) 4 return 0; 5 if(num.length == 1) 6 return num[0]; 7 int result[] = new int[num.length]; 8 result[0] = num[0]; 9 result[1] = num[0] > num[1] ? num[0] : num[1]; 10 for(int i = 2; i < num.length; i++){ 11 result[i] = result[i - 1] > (result[i - 2] + num[i]) ? result[i - 1] : (result[i - 2] + num[i]); 12 } 13 14 return result[num.length - 1]; 15 } 16 }
标签:
原文地址:http://www.cnblogs.com/luckygxf/p/4396501.html