求非负整数数组中取一些元素的和的最大值,要求不能取相邻的元素
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.
简单的DP算法
递推公式
dp[i] = dp[i-2]+help[i-1]>dp[i-3]+help[i-2]?dp[i-2]+help[i-1]:dp[i-3]+help[i-2];
i表示取到数组范围[0, i-1],(不一定包含help[i-1]),例如dp[4] = dp[1]+help[2]或者dp[2]+help[3];
算法:
class Solution {
public:
int rob(vector<int>& nums) {
int n = nums.size();
help = nums;
return f(n);
}
int f(int n){
int *dp = new int[n+1];
if(n == 0){
return 0;
}
dp[0] = 0;
if(n == 1){
return help[0];
}
dp[1] = help[0];
if(n == 2){
return dp[1]>help[1]?dp[1]:help[1];
}
dp[2] = dp[1]>help[1]?dp[1]:help[1];
if(n == 3){
return dp[1]+help[2]>dp[2]?dp[1]+help[2]:dp[2];
}
dp[3] = dp[1]+help[2]>dp[2]?dp[1]+help[2]:dp[2];
for(int i = 4; i <=n; i++){
dp[i] = dp[i-2]+help[i-1]>dp[i-3]+help[i-2]?dp[i-2]+help[i-1]:dp[i-3]+help[i-2];
}
return dp[n];
}
private:
vector<int> help;
};
测试代码
#include "stdafx.h"
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
int rob(vector<int>& nums) {
int n = nums.size();
help = nums;
return f(n);
}
int f(int n) {
vector<int> dp(n + 1, 0);
if (n == 0) {
return 0;
}
dp[0] = 0;
//cout << "dp[0]:" << dp[0] << endl;
if (n == 1) {
return help[0];
}
dp[1] = help[0];
//cout << "dp[1]:" << dp[1] << endl;
if (n == 2) {
return dp[1]>help[1] ? dp[1] : help[1];
}
dp[2] = dp[1]>help[1] ? dp[1] : help[1];
//cout << "dp[2]:" << dp[2] << endl;
if (n == 3) {
return dp[1] + help[2]>dp[2] ? dp[1] + help[2] : dp[2];
}
dp[3] = dp[1] + help[2]>dp[2] ? dp[1] + help[2] : dp[2];
//cout << "dp[3]:" << dp[3] << endl;
for (int i = 4; i <= n; i++) {
dp[i] = dp[i - 2] + help[i - 1]>dp[i - 3] + help[i - 2] ? dp[i - 2] + help[i - 1] : dp[i - 3] + help[i - 2];
//cout << "dp["<<i<<"]:" << dp[i] << endl;
}
return dp[n];
}
private:
vector<int> help;
};
int main() {
int n;
cin >> n;
vector<int> vec(n, 0);
for (int i = 0; i < n; i++) {
cin >> vec[i];
}
Solution s;
cout << s.rob(vec);
system("pause");
return 0;
}