Std :: stack <int> with maximum function?

How to implement stack<int>with the maximum operation, which has the maximum function O (1), and uses O (n) additional memory?

+4
source share
3 answers

The idea would be to track the maximum length using pairs on the stack. If you push something onto the stack, you update max accordingly.

class Stack {
private: 
    stack<pair<int,int>> s;

public:
    bool empty() const {
        return s.empty();
    }

    int max() const {
        assert (empty() == false);
        return s.top().second;
    }

    int pop() {
        int ans = s.top().first;
        s.pop();
        return ans;
    }

    void push(int x) {
        if (s.empty() || x > s.top().second)
        {
            s.emplace(x, x);
        }
        else
        {
            s.emplace(x, s.top().second);
        }
    }
};
+6
source

Keep sorted listoutint

Each node stack points to an entry list

maxjust returns the head ( minwill be the tail)list

push list (, O (n), )

pop list

- O (1). list O (n).

+2

2 , . ( max_stack).

max_stack, max_stack. pop max_stack, , , max_stack. top max_stack .

: 2,1,2,1,3,2,3, max_stack 2,2,3,3.

+2
source

Source: https://habr.com/ru/post/1618183/


All Articles