Greedy
Greedy
for(k steps)
{
if(first element > last element)
remove first element
else
remove last element
}
ll i=0,j=n-1;
Code And ll ans =0;
Logic while(k>0){
if(v[i]>=v[j]){
ans+=v[i];
Here we use the two pointer - i++;
We would compare the first and }
last element in the array and else{
this would result to our answer . ans+=v[j];
j--;
}
k--;
}
cout<<ans<<"\n";
Does greedy work always ??
NO!!!!!!!!!!!!!
!
Consider the case:-
a= 1 100 3 4 5 6
k=2
Apply the greedy algorithm
i) Step 1:- last = 6 && first = 1; so remove last
=6
ii) Step 2:- last = 5 && first = 1; so remove last
=5
But, by inspection we can remove the first two elements =
Sum of removed numbers = 6 + 5 = 11
1 & 100
Now, sum of removed elements = 101
Observation
After removing k elements, we will have a subarray of length n -
k.
Now,
Sum of removed elements + Sum of the remaining subarray =
Sum of all elements
20 50 100 200
N=
X= 520
Here the required money can be generated by
taking {200,200,100,20}
Sample-
N= 1 3 4
X=6