Largest Rectangle

  • + 0 comments

    Java O(n)

    public static long largestRectangle(List<Integer> h) {
            Stack<Integer> stack = new Stack<>();
            long maxArea = 0;
            int n = h.size();
    
            for (int i = 0; i < n; i++) {
                while (!stack.isEmpty() && h.get(stack.peek()) >= h.get(i)) {
                    int height = h.get(stack.pop());
                    int width = stack.isEmpty() ? i : i - stack.peek() - 1;
                    maxArea = Math.max(maxArea, (long) height * width);
                }
                stack.push(i);
            }
    
            while (!stack.isEmpty()) {
                int height = h.get(stack.pop());
                int width = stack.isEmpty() ? n : n - stack.peek() - 1;
                maxArea = Math.max(maxArea, (long) height * width);
            }
            return maxArea;
        }