You have to give a data structure to implement push & pop (as like a simple satck ) in O(1) time &
find minimum of the current stack also in O(1) time.
Solution :
push(x)
{
if(stack.isEmpty())
{
stack.push(x);
stack.push(x);
}
else
{
if(x > stack.top)
{
min=stack.top;
stack.push(x);
stack.push(min);
}
else
{
stack.push(x);
stack.push(x);
}
}
}
int pop()
{
stack.pop();
return (stack.pop());
}
int min()
{
return stack.top;
}
find minimum of the current stack also in O(1) time.
Solution :
push(x)
{
if(stack.isEmpty())
{
stack.push(x);
stack.push(x);
}
else
{
if(x > stack.top)
{
min=stack.top;
stack.push(x);
stack.push(min);
}
else
{
stack.push(x);
stack.push(x);
}
}
}
int pop()
{
stack.pop();
return (stack.pop());
}
int min()
{
return stack.top;
}
0 comments:
Post a Comment