Objective Find minimum value in stack in O(1) time complexity.
Issue : Failing at the below operation (2*x-minEle) in some Leetcode testcases.
Actual Error - runtime error: signed integer overflow: 2 * -2147483648 cannot be represented in type 'int'
I tried replacing every integer value with long long datatype but still getting the same error
Following is the code:
class MinStack {
public:
int minEle = INT_MAX;
vector<int> s;
void push(int x) {
if(s.empty())
{
minEle=x;
s.push_back(x);
return;
}
if(x<minEle)
{
s.push_back(2*x-minEle);
minEle = x;
}
else
s.push_back(x);
}
void pop() {
int y = s.back();
if(y<minEle)
{
minEle = 2*minEle - y;
}
s.pop_back();
}
int top() {
return s.back();
}
int getMin() {
return minEle;
}
};