714167. Maximum Identical Bowls

Easy

Here is the detailed Markdown blog post for the problem "Maximum Identical Bowls":

Maximum Identical Bowls

Summary

The problem is about finding the maximum number of identical bowls that can be stacked on top of each other in a given array. The array represents the heights of the bowls, and we need to find the maximum height stack by considering only the identical bowls.

Detailed Explanation

Let's break down the problem step-by-step:

  1. Initialize an empty stack maxStack and a variable maxHeight set to 0.
  2. Iterate through the array of bowl heights from left to right.
  3. For each bowl, check if it is taller than the topmost bowl in maxStack. If not, pop the topmost bowl from maxStack until we find a bowl that is identical to the current one or the stack becomes empty.
  4. If the current bowl is taller than any bowl in maxStack, push it onto the stack and update maxHeight.
  5. Repeat steps 2-4 until we have processed all bowls.
  6. The maximum height stack found during the iteration is the answer.

Here's a diagram illustrating the process:

  Bowl Heights: [3, 1, 2, 2, 3, 1]
  Stack: []
  maxHeight: 0

  Iterate through the array:
  * 3 (taller than stack, push onto stack and update maxHeight)
    Stack: [3]
    maxHeight: 3
  * 1 (shorter than topmost bowl in stack, pop from stack)
    Stack: []
    maxHeight: 3
  * 2 (identical to topmost bowl in stack, push onto stack and update maxHeight)
    Stack: [2]
    maxHeight: 3
  * 2 (identical to topmost bowl in stack, push onto stack)
    Stack: [2, 2]
    maxHeight: 4
  * 3 (taller than any bowl in stack, push onto stack and update maxHeight)
    Stack: [2, 2, 3]
    maxHeight: 5
  * 1 (shorter than topmost bowl in stack, pop from stack)
    Stack: [2, 2, 3]
    maxHeight: 5

  The maximum height stack found is [2, 2, 3], with a height of 5.

Time complexity: O(n), where n is the number of bowls. Space complexity: O(h), where h is the maximum height of the bowls.

Optimized Solutions

Java
View on GeeksforGeeks
public int maxIdenticalBowls(int[] heights) {
    int maxHeight = 0;
    Stack<Integer> stack = new Stack<>();
    
    for (int height : heights) {
        while (!stack.isEmpty() && stack.peek() < height) {
            stack.pop();
        }
        
        if (stack.isEmpty() || stack.peek() == height) {
            stack.push(height);
            maxHeight = Math.max(maxHeight, height);
        } else {
            break;
        }
    }
    
    return maxHeight;
}

DevExCode

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

© 2026 DevExCode. All rights reserved.