Stack and Queue <Nissan>

3.5

63 votes
Arrays, Data Structures, Easy, Implementation, Queue, Stacks
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

Constraints :

  • 1N105
  • 1KN
  • 1Ai109
Time Limit: 1
Memory Limit: 256
Source Limit:
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

Editor Image

?