假设你是一个专业的窃贼,准备沿着一条街打劫房屋。每一个房子都存放着特定金额的钱。你面临的惟一约束条件是:相邻的房子装着相互联系的防盗系统,且 当相邻的两个房子同一天被打劫时,该系统会自动报警。
给定一个非负整数列表,表示每一个房子中存放的钱, 算一算,若是今晚去打劫,在不触动报警装置的状况下,你最多能够获得多少钱。测试
给定 [3, 8, 4], 返回 8.code
思路:
若是选择了抢劫上一个屋子,那么就不能抢劫当前的屋子,因此最大收益就是到上一个屋子为止的最大收益;
若是选择抢劫当前屋子,就不能抢劫上一个屋子,因此最大收益是到上上一个屋子为止的最大收益,加上当前屋子里有的钱。it
class Solution { public: /* * @param A: An array of non-negative integers * @return: The maximum amount of money you can rob tonight */ long long houseRobber(vector<int> &A) { // write your code here int n = A.size(); if(n==0) return 0; if(n==1) return A[0]; /*前一次最大收益*/ long int last_max = A[0]; /*当前最大收益,指的是没有打劫第i间屋子的最大收益*/ long int current_max = max(A[0],A[1]); /*遇到下一个房间,判断如何选择*/ for(int i=2; i<n; i++) { long int temp = current_max; //决定要不要打劫第i间屋子 current_max= max(current_max, last_max+A[i]); last_max = temp; //cout<<n<<" "<<current_max<<endl; /*逗,有个测试用例的数据特别大,int类型装不下,因此不经过。*/ } return current_max; } };