Compute Maximum Area Under Adjacent Bars
Company: Zipline
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates proficiency in array algorithms, range-based aggregation, and algorithmic optimization, including efficient data structure usage and complexity analysis for large inputs.
Constraints
- 1 <= n <= 100000
- 0 <= heights[i] <= 1000000000
- The answer may require 64-bit integer arithmetic (height up to 1e9 times width up to 1e5 ⇒ up to 1e14).
Examples
Input: ([2, 1, 5, 6, 2, 3],)
Expected Output: 10
Explanation: Bars 5 and 6 form height 5 over width 2 = 10.
Input: ([2, 4],)
Expected Output: 4
Explanation: Single bar of height 4 gives 4; pairing both gives height 2 over width 2 = 4.
Input: ([6, 2, 5, 4, 5, 1, 6],)
Expected Output: 12
Explanation: Bars at indices 2..4 (5,4,5) give height 4 over width 3 = 12.
Input: ([0],)
Expected Output: 0
Explanation: Single zero-height bar yields area 0.
Input: ([5],)
Expected Output: 5
Explanation: Single bar: height 5 over width 1 = 5.
Input: ([3, 3, 3, 3],)
Expected Output: 12
Explanation: All equal: height 3 over the full width 4 = 12.
Input: ([1, 2, 3, 4, 5],)
Expected Output: 9
Explanation: Strictly increasing: best is height 3 over width 3 (3,4,5) = 9.
Input: ([5, 4, 3, 2, 1],)
Expected Output: 9
Explanation: Strictly decreasing: best is height 3 over width 3 (5,4,3) = 9.
Input: ([1000000000, 1000000000, 1000000000],)
Expected Output: 3000000000
Explanation: Three max-height bars give 1e9 * 3 = 3e9, requiring 64-bit arithmetic.
Hints
- For each bar, ask: what is the widest contiguous span in which this bar is the shortest? Its height times that width is a candidate area.
- Use a stack that holds bar indices in non-decreasing height order. When the current bar is shorter than the bar on top of the stack, that top bar can no longer extend rightward — pop it and compute its area.
- When popping index `top`, the rectangle height is `heights[top]`; its left boundary is the new stack top (after popping) and its right boundary is the current index `i`, so width = `i - stack[-1] - 1` (or `i` if the stack is empty).
- Append a sentinel bar of height 0 at the end (iterate to index n) so every remaining bar in the stack gets flushed and measured.