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.
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.