参考: https://blog.youkuaiyun.com/realxie/article/details/8063885
题目:
给定一个数组A,求出一些数,使得每个元素在数组A里两两不相邻,并且和最大。
- 选择第i个元素,那么第i-1个元素一定不能选
- 不选择第i个元素,那么第二个元素既可以选,也可以不选
#include<bits/stdc++.h>
using namespace std;
int main(){
int input[8]={1,7,4,0,9,4,8,8};
int selected[8];
int notselected[8];
selected[0] = input[0];
notselected[0]=0;
for(int i = 1; i < 8; i++){
selected[i] = notselected[i-1] + input[i];
notselected[i] = max( selected[i-1], notselected[i-1]);
}
for(int i = 0; i < 8;i++){
cout<<selected[i]<<" ";
}
cout<<endl;
for(int i = 0; i < 8;i++){
cout<<notselected[i]<<" ";
}
cout<<endl;
cout<<"ans:"<<max(selected[7], notselected[7]);
return 0;
}
或者
f[0] = max (0, input[0])
f[1] = max (input[1], f[0])
f[n] = max (f[n-2]+input[n], f[n-1])