I can think of recursive solution. But it would have exponential time complexity.
int sum,n;
ll best = -1;
void rec(int id, vi &a, int temp){
if(id>=n){
if(temp>=best && temp<=sum) best = sum;
return;
}
rec(id+2, a, temp+a[id]); // if we include i'th we need to skip i+1'th
rec(id+1, a, temp); // if we not include i'th we can take i+1'th
}
int main(){
cin>>n;
vi a(n);
for(int i=0;i<n;i++) cin>>a[i];
cin>>sum;
rec(0, a, 0);
cout<<best<<"\n";
}
I think there might be some greedy or dp approach to solve it in linear time.
@shadab_shaikh1 No, this will find the max sum, but we are interested in max sum less than or equal to a given sum. I have used similar approach in my solution, but this is not giving the right answer.
I took dp[0][i] to include the ith element and dp[1][i] to exclude the ith element and output ans is max(dp[0][n-1],dp[1][n-1]
#include<bits/stdc++.h>
using namespace std; #define ll long long
int main()
{
int n;
cin>>n;
ll int dp[2][n+1];
ll int a[n];
for(int i=0;i<n;i++)
cin>>a[i];
for(int i=0;i<=n;i++)
{
dp[0][i]=0;
dp[1][i]=0;
}
#include<bits/stdc++.h>
using namespace std; #define ll long long
int main()
{
int n;
cin>>n;
ll int dp[2][n+1];
ll int a[n];
for(int i=0;i<n;i++)
cin>>a[i];
for(int i=0;i<=n;i++)
{
dp[0][i]=0;
dp[1][i]=0;
}
If we ignore the <= sum conditional and just try to find the max sum with no adjecent elements, I have a question.
In this, we are taking the max between the sum of the ith element of array plus the i-2th element of dp array and the i-1th element of the dp array. But it could be the case that the i-1th element was not used to make the sum at dp[i-1]. If that is the case, we could technically add the ith element to this too right? Can someone explain why this isn’t necessary?