ADS Lab Stack - NGE Stockspan
ADS Lab Stack - NGE Stockspan
Q1.
Given a linear list, print the Next Greater Element (NGE) for every
element. The NGE for an element x is the first greater element on the
right side of x in the list. Elements for which no greater element exist,
consider NGE as -1.
Examples:
a) For any list, rightmost element always has next greater element as -1.
b) For any list which is sorted in decreasing order, all elements have next
greater element as -1.
c) For the input list 4 -> 5 -> 2 -> 25 the next greater elements for each element are
as follows.
NGE of 4 is 5, NGE of 5 is 25
NGE of 2 is 25, NGE of 25 is -1
d) For the input list 13 -> 7 -> 6 -> 12 the NGE for each element are as follows.
NGE of 13 is -1, NGE of 7 is 12
NGE of 6 is 12, NGE of 12 is -1
1. Push the first element to stack.
2. Pick rest of the elements one by one and follow the below steps in loop.
a) Mark the current element as next.
b) If stack is not empty, then compare top element of stack with next.
i. If next is greater than the top element, then next is the NGE for the top element. Pop
the top element.
ii. Keep popping from the stack while the popped element is smaller than next. next
becomes the NGE for all such popped elements
c) Finally, push the next to the stack.
3. After the loop in step 2 is over, pop all the elements from stack and print -1 as NGE for them.
4 -> 5 -> 2 -> 25
The span Si of the stock’s price on a given day i is defined as the maximum
number of consecutive days on or just before the given day i, for which the
price of the stock is less than or equal to its price on the given day i.