0

This algorithm takes as input a vector of integers and will store the max first, let's stay its position is p in the array, then we store the max element in the range [p, n[ and so on.

// input v[0]...v[n-1] is a vector of integers already filled.
// output : stack s 
stack<int> s;
for(auto x: v){
     while(!s.empty() && x > s.top()) s.pop();
     s.push(x);
}

I can't figure out the worst case, but it seems the algorithm is linear, because the more the while() will work the more the stack size will be reduced and make the future work very cheap.

1 Answer 1

1

Worst Case

Your program is to have the max value at the bottom of the stack. You will perform push() operation N time. At worst case, you will pop() N-1 times . (because you cannot pop more than N-1 times or else you will have empty stack and it is against the program purpose).

Best Case

The best case would be when the max value at the first element of the vector V. You still perform N push() operation and will never perform any pop() operation.

So at the end of the day, regardless of any data in vector V, it will perform at the linear time.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.