Given an array of positive numbers, find the maximum subsequence sum <= given sum, such that no two elements are adjacent to each other

橙三吉。 提交于 2019-12-24 22:27:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!