标签:
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.
Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases.
1 public class Solution 2 { 3 public static int rob(int[] num) 4 { 5 int a=0; 6 int b=0; 7 for(int i=0;i<num.length;i++) 8 { 9 if(i%2==0) 10 a=Math.max(a+num[i],b); 11 else 12 b=Math.max(a,b+num[i]); 13 } 14 return Math.max(a, b); 15 } 16 public static void main(String args[]) 17 { 18 // System.out.println("---"); 19 int[]num={226,174,214,16,218,48,153,131,128,17,157,142}; 20 int sum=rob(num); 21 System.out.println(sum); 22 } 23 }
1 public int rob(int[] num) { 2 int n = num.length; 3 if (n < 2) 4 return n == 0 ? 0 : num[0]; 5 int[] cache = new int[n]; 6 cache[0] = num[0]; 7 cache[1] = num[0] > num[1] ? num[0] : num[1]; 8 for (int i = 2; i < n; i++) { 9 cache[i] = cache[i - 2] + num[i]; 10 cache[i] = cache[i] > cache[i-1]? cache[i] : cache[i-1]; 11 } 12 return cache[n - 1]; 13 }
标签:
原文地址:http://www.cnblogs.com/qq1029579233/p/4401704.html