888468. Get Max from Stack

Medium

Get Max from Stack

Summary

The problem "Get Max from Stack" requires you to find the maximum value in a stack. The input is an array representing the stack, and your task is to write a function that returns the maximum value without popping all elements from the stack.

This problem involves working with stacks, which are a fundamental data structure in computer science. It also requires thinking about how to efficiently find the maximum value without modifying the original order of the stack.

Detailed Explanation

To solve this problem, we can use a simple iterative approach. We initialize our maximum value as the first element of the stack and then iterate through the rest of the stack. For each element, we compare it with our current maximum value and update it if necessary. This way, we effectively find the maximum value without having to pop all elements from the stack.

Here's a step-by-step breakdown of the solution:

  1. Initialize max as the first element of the input array.
  2. Iterate through the rest of the array (starting from the second element).
  3. For each element, compare it with max. If the current element is greater than max, update max.
  4. Return max as the maximum value in the stack.

Time complexity: O(n), where n is the size of the input array. Space complexity: O(1) because we only use a constant amount of space to store the maximum value.

Optimized Solutions

Java

View on GeeksforGeeks
public int getMax(int[] stack) {
    int max = stack[0];
    for (int i = 1; i < stack.length; i++) {
        if (stack[i] > max) {
            max = stack[i];
        }
    }
    return max;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.