Suggest an algo to solve this problem

You don`t need to store the stack.
If n=1 and k is odd then stack will be empty.
if n<=k then input all and output the max element.
if n>k then input first to k-1,k+1 and output max(max(first to k-1) , k+1 th element) : (k-th element always pop)

could you plz explain me the logic

According to question you need to o/p the top which is max achievable after exactly k operations.
If we Pop and Push the top then we could reduce k by 2. So, if k is one for any element then it will be poped or pushed by another element. And for if k is greater than one for any element then we can make it top .
if k >n then every element must have greater than one operation left and the top will be the max in array.
if k<=n then k-th element must be k=1 operation left and either be pop or push. So, we will ignore the k-th element and find the top from first to k+1 th position. Ex: -
n=10 k=8
1 ,2 ,3 ,4 ,5 ,6 ,7 ,999999 ,8 ,9
ans :- 8.

1 Like