问题
This is my code
It passes for few cases but not for all, for eg.
number of elements n = 6
elements a[n] = {5,5,10,100,10,5}
and sum = 25
the output is 15, but output should be 25 (5 + 10 + 10)
click here to see its working in IDE
#include<bits/stdc++.h>
#define ll long long int
using namespace std;
int main(){
int n;
ll sum;
vector<ll> v;
cin>>n;
ll a[n];
for(int i=0;i<n;i++){
cin>>a[i];
}
cin>>sum;
ll ans = 0;
ll inc = a[0];
ll exc = 0;
ll prev = 0;
for(int i=1;i<n;i++){
prev = inc;
inc = max(exc+a[i],a[i]);
exc = max(prev,exc);
// cout<<inc<<" "<<exc<<endl;
ll ans1 = max(inc,exc);
if(ans1<=sum){
ans = max(ans1,ans);
}
}
cout<<ans<<endl;
return 0;
}
来源:https://stackoverflow.com/questions/58824571/given-an-array-of-positive-numbers-find-the-maximum-subsequence-sum-given-su