int getMax(int a[],int len)
{
int max1 = a[0];//表示maxSum(n-2);
int max2 = a[0]>a[1]? a[0]:a[1]; //表示maxSum(n-1);
int max3 = 0; // n
for(int i =2; i<len; i++){
if(max1<0){
max3 = a[i] > max2 ? a[i]:max2;
}else{
max3 = a[i]+max1> max2 ? a[i]+max1:max2; }
max1 = max2;
max2 = max3;
}
return max3;
}
int maxSum(vector<int> array) { if (array.size() == 0) return 0; int fi = array[0], hi = 0; for (int i=1; i<array.size(); i++) { int nfi = hi + array[i]; hi = max(hi, fi); fi = nfi; } return max(hi, fi); }
#include <iostream>#include <vector>#include <string>#include <algorithm>#include <map>using namespace std;struct record{int number;int index;int valid;};int cmp(const record &a, const record &b){return a.number < b.number;}int main(void){vector<record> input;int number, idx = 0;while(cin >> number){record rec = {number, idx++, 1};input.push_back(rec);}sort(input.begin(), input.end(), cmp);vector<int>::size_type sz = input.size();map<int, int> mask;for(vector<int>::size_type i = 0; i < sz; ++i)mask.insert(make_pair(input[i].index, i));vector<int>::size_type i = sz - 1;int sum = 0;if(input[i].number <= 0)sum = input[i].number;else{while(i >= 0 && input[i].number > 0){vector<int>::size_type idx1, idx2;if(!input[i].valid){i--;continue;}sum += input[i].number;idx1 = input[i].index - 1;idx2 = input[i].index + 1;if(idx1 >= 0)input[mask[idx1]].valid = 0;if(idx2 < sz)input[mask[idx2]].valid = 0;i--;}}cout << sum << endl;return 0;}算法渣。排序+剔除
{
int max1 = a[0];//表示maxSum(n-2);
int max2 = a[0]>a[1]? a[0]:a[1]; //表示maxSum(n-1);
int max3 = 0; // n
for(int i =2; i<len; i++){
max3 = Max(a[i],Max(max1+a[i],max2));
// max3 = a[i]+max1> max2 ? a[i]+max1:max2; // 全部是负数也需要考虑的,这个没有
max1 = max2;
max2 = max3;
}
return max3;
}
int Max(int a,int b){
if(a>b)
return a;else
return b;
}