Problem-
You are given a stack of N integers such that the first element represents the top of the stack and the last element represents the bottom of the stack. You need to pop at least one element from the stack. At any one moment, you can convert stack into a queue. The bottom of the stack represents the front of the queue. You cannot convert the queue back into a stack. Your task is to remove exactly K elements such that the sum of the K removed elements is maximised.
Input format :
The first line consists of two space-separated integers N and K.
The second line consists of N space-separated integers denoting the elements of the stack.
Output format :
Print the maximum possible sum of the K removed elements
SAMPLE INPUT
10 5
10 9 1 2 3 4 5 6 7 8
SAMPLE OUTPUT
40
Explanation
Pop two elements from the stack. i.e {10,9}
Then convert the stack into queue and remove first three elements from the queue. i.e {8,7,6}.
The maximum possible sum is 10+9+8+7+6 = 40
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
#include<iostream>
using namespace std;
long long int ans=0,currentsum;
int n,k,arr[100000];
int answer(int x)
{
int ilimit=x-1;
int jlimit=n-k+x+1;
currentsum=0;
for(int i=0;i<=ilimit;i++)
currentsum+=arr[i];
for(int j=n;j>=jlimit;j--)
currentsum+=arr[j];
if(currentsum>ans)
ans=currentsum;
return 0;
}
int main()
{
cin>>n>>k;
for(int i=0;i<n;i++)
cin>>arr[i];
n--;
for(int x=1;x<=k;x++)
answer(x);
cout<<ans;
return 0;
}
|
Issue-
I am getting time limit exceeded for some cases
My logic-
Find answer by going through all possible arrangements.
like for n=10 k=5
i=0 1 2 3 4
i=0 1 2 3 4 j=9
i = 0 1 2 3 j = 9 8
and so on