Stack of Integers
You are given a sequence of integers. You process them one by one. If the stack is empty, push the current integer. If the stack is not empty, compare the current integer with the integer at the top of the stack.
- If the current integer is greater than the top element, pop the top element.
- If the current integer is less than or equal to the top element, push the current integer. After processing all integers, if the stack is not empty, print the integer at the top of the stack. If the stack is empty, print 0.
Input
The first line contains an integer N, the number of integers in the sequence. The second line contains N space-separated integers.
Output
Print a single integer: the top element of the stack after processing all inputs, or 0 if the stack is empty.
Constraints
1 <= N <= 1000 -10^9 <= integer value <= 10^9
Example 1
5 3 1 4 1 5
3
Stack operations: push 3 -> [3]; 1 <= 3, push 1 -> [3, 1]; 4 > 1, pop 1 -> [3]; 4 > 3, pop 3 -> []; 1 <= empty, push 1 -> [1]; 5 > 1, pop 1 -> []. Final stack empty, output 0.
Example 2
6 2 5 3 7 4 8
0
Stack operations: push 2 -> [2]; 5 > 2, pop 2 -> []; push 3 -> [3]; 7 > 3, pop 3 -> []; push 4 -> [4]; 8 > 4, pop 4 -> []. Final stack empty, output 0.
Hints
# Read the input from stdin and print the answer.
import sys
def main():
data = sys.stdin.read().split()
# your code here
main()
5 3 1 4 1 5
6 2 5 3 7 4 8