Home > AI > Data Structure > Stack >

(HackerRank) Maximum Element

https://www.hackerrank.com/challenges/maximum-element/problem

Solution (Java)

import java.util.*;

public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */

        Scanner in = new Scanner(System.in);
        int num = in.nextInt();
        in.nextLine();



        MyStack s = new MyStack(num);
        for (int i=0; i<num; i++) {
            String line = in.nextLine();

            String[] lines = line.split(" ");

            if (Integer.valueOf(lines[0]) == 1) {
                s.push(Integer.valueOf(lines[1]));

            } else if (Integer.valueOf(lines[0]) == 2) {
                s.pop();

            } else if (Integer.valueOf(lines[0]) == 3) {
                System.out.println(s.peek().curMax);
            }
        }

        in.close();

    }
}




class MyStack {
    MyStackNode[] data;
    int top = 0;
    int mx = Integer.MIN_VALUE;


    public MyStack(int size) {
        data = new MyStackNode[size];
    }

    public void push(int x) {
        if (isFull()) {
            System.out.println("This stack is full");
        } else {
            // update max;
            mx = Integer.max(mx, x);
            MyStackNode n = new MyStackNode(x, mx);
            data[top] = n;
            top++;
        }
    }

    public MyStackNode pop() {
        if (isEmpty()) {
            System.out.println("This stack is empty");
            return null;
        } else {
            MyStackNode n = data[top-1];
            top--;

            // update mx
            if (isEmpty()) {
                mx = Integer.MIN_VALUE;
            } else {
                mx = data[top-1].curMax;
            }

            return n;
        }
    }

    public MyStackNode peek() {
        if (isEmpty()) {
            System.out.println("This stack is empty");
            return null;
        } else {
            return data[top - 1];
        }
    }

    public boolean isEmpty() {
        if (top == 0) {
            return true;
        } else {
            return false;
        }

    }

    public boolean isFull() {
        if (top == data.length ){
            return true;
        } else {
            return false;
        }
    }


    public void show() {
        if (isEmpty()) {
            System.out.println("This stack is empty");
        } else {
            for (int i=0; i<data.length; i++) {
                System.out.println(data[i].val);
            }
        }
    }
}


class MyStackNode {
    int val;
    int curMax;

    MyStackNode(int val, int curMax) {
        this.val = val;
        this.curMax = curMax;
    }
}

Leave a Reply