Stack operations

You are given a stack of N integers. In one operation, you can either pop an element from the stack or push any popped element into the stack. You need to maximize the top element of the stack after performing exactly K operations. If the stack becomes empty after performing K operations and there is no other way for the stack to be non-empty, print -1.

Example:

Input: n = 6, k = 4, a[n] = {1, 2, 4, 3, 3, 5}
Output: 4

Approach

C++

#include <bits/stdc++.h>
using namespace std;

int main()
{

    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    long long n = 6k = 4;
    long long a[n] = {124335};

    if (n == 1)
    {
        if (k % 2 == 0)
            cout << a[0];
        else
            cout << "-1";
    }

    else if (k == 1)

        cout << a[1];

    else if (k < n)
    {
        cout << max(*max_element(aa + k - 1), a[k]);
    }
    else if (k == n)
    {
        cout << *max_element(aa + n - 1);
    }
    else
        cout << *max_element(aa + n);

    return 0;
}


No comments:

Post a Comment