Stack Maximum Element and performance

Problem Source: Maximum Element – Hackerrank

You have an empty sequence, and you will be given N queries. Each query is one of these three types:

1 x  -Push the element x into the stack.
2    -Delete the element present at the top of the stack.
3    -Print the maximum element in the stack.

Input Format

The first line of input contains an integer, N. The next N lines each contain an above mentioned query. (It is guaranteed that each query is valid.)

Constraints

1 <= N <= 10^5

1 <= x <= 10^9

Sample Input:

10
1 97
2
1 20
2
1 26
1 20
2
3
1 91
3

Sample Output

26
91

C# code:

class Test
{
    class CustomStack
    {
        public long Value { getset; }
        public long MaxValue { getset; }
    }
    static void Main(string[] args)
    {
        int N = Convert.ToInt32(Console.ReadLine());
        Stack<CustomStack> st = new Stack<CustomStack>();
        long maxInStack = 0;
        for (int i = 0; i < N; i++)
        {
            string[] str = Console.ReadLine().Split(' ');
            if (str[0] == "1")
            {
                long temp = Convert.ToInt64(str[1]);
                CustomStack cusSt = new CustomStack();
                if (temp > maxInStack)
                {
                    maxInStack = temp;
                }
                cusSt.Value = temp;
                cusSt.MaxValue = maxInStack;
                st.Push(cusSt);
            }
            else if (str[0] == "2")
            {
                st.Pop();
                if (st.Count > 0)
                {
                    maxInStack = st.Peek().MaxValue;
                }
                else
                {
                    maxInStack = 0;
                }
            }
            else if (str[0] == "3")
            {
                maxInStack = st.Peek().MaxValue;
                Console.WriteLine(maxInStack);
            }
        }
 
        Console.ReadKey();
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s