Largest histogram rectangle
Return the largest rectangle area under nonnegative unit-width histogram bars in linear time. Empty input returns zero.
height, right, previous_smaller = 5, 4, 1
width = right-previous_smaller-1
print(height*width)Reason about the state
Keep indices of increasing heights. A lower incoming bar fixes the right boundary for popped heights; the new stack top fixes their left boundary. Before writing code, identify what each variable means after one iteration. Walk through the example and explain why the next transition preserves that meaning. Then check the smallest permitted input and a case with repeated values. A correct answer follows the contract for every input, including the boundary cases in the checks. Keep any input mutation within the stated rules; return a fresh result when the task asks for one.
Your task
Return the largest rectangle area under nonnegative unit-width histogram bars in linear time. Empty input returns zero.
The explanation opens here once every check passes.