0

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;
}
Mohit
  • 590
  • 5
  • 13
  • 3
    1) `#include` -- Use the proper headers, not this one. 2) `#define ll long long int` -- Not this, please. 3) `vector v; cin>>n;ll a[n];` -- You have vector, then for some odd reason, you use non-standard C++ here: `a[n]`, when you could have used vector there also. – PaulMcKenzie Nov 12 '19 at 18:33
  • [For the sake of others who may want to help, here is a cleaned up version of your code](https://coliru.stacked-crooked.com/a/5a7776a55982849b). Note there are no input statements, no non-standard headers, no non-standard C++ syntax, and no funny macros. – PaulMcKenzie Nov 12 '19 at 18:57
  • Possible duplicate of https://stackoverflow.com/questions/4487438/maximum-sum-of-non-consecutive-elements – User_67128 Nov 15 '19 at 12:39
  • @ManojBanik No, its not duplicate, in this question we need to find maximum less than or equal to given number. – Mohit Nov 16 '19 at 14:20

0 Answers0