Implement min stack

Implement a stack that has the following methods:

  • push(val), which pushes an element onto the stack
  • pop(), which pops off and returns the topmost element of the stack. If there are no elements in the stack, then it should throw an error or return null.
  • max(), which returns the maximum value in the stack currently. If there are no elements in the stack, then it should throw an error or return null.

Each method should run in constant time

Example:

Input:  push = [-20,0,-3]
Output: -20

Approach

C++

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

vector<intv;
int min1 = INT_MAX;

void push(int x)
{
    if (x < min1)
        min1 = x;
    v.push_back(x);
}

int top()
{
    return v[v.size() - 1];
}

void pop()
{
    int x = top();
    v.pop_back();
    if (x == min1)
    {
        min1 = INT_MAX;
        for (int i : v)
        {
            if (i < min1)
                min1 = i;
        }
    }
}

int getMin()
{
    return min1;
}

int main()
{
    push(-20);
    push(0);
    push(-3);
    cout << getMin();

    return 0;
}


No comments:

Post a Comment