Proofs: Histogram stack algorithm
These are the human proofs of Histogram stack algorithm, at full length.
The histogram stack algorithm returns the largest rectangle full
This proof shows: correctness.
We use the pseudocode of the page on heights , and we set , the value that line L3 uses at . For let , and let be the largest such area, or if . Write the stack from the bottom as and set .
Lemma 1 (invariants). At the start of each step ():
- and ;
- for , every with has ;
- if , then and .
Proof. At the stack is empty. Suppose the lemma holds at the start of step and look at the stack just before line L8 of that step, with . The pops removed exactly , and they all have , while if , since the loop stopped. Line L8 pushes . Part 1 holds for the new stack, since . For part 2 with the new top , the bars with are the popped , each with , and the bars between them, each at least as high as the popped bar above it by part 2; so all have . The other parts of part 2 do not change. Part 3 holds since is on top.
Lemma 2 (each recorded area is real). When line L7 runs for at step with from line L6, every bar with has . So if , and .
Proof. At the pop, and for the stack at that moment, which is a prefix of the stack at the start of step , so Lemma 1 applies to it. Bars with have by part 2. Bars with are the stack items above at the start of the step, which are higher than by part 1, and the bars between them, which are at least as high as some such item by part 2, with the last item by part 3. The lowest bar of is then itself.
Lemma 3 (when a bar is popped). Bar is popped at step , the least with and , and at that moment , the largest with , or .
Proof. Bar is pushed at step . At a later step with , the pops stop at or above it, because every item above is higher than and the loop stops at the first item lower than ; so stays. At the first step with , every item above is higher than , so all of them and then are popped. Now has by part 1, and every bar between and has by part 2, so .
At the value for every , so always exists.
Theorem. LARGEST-RECTANGLE returns .
Proof. By Lemma 2, every value that line L7 compares is the area of a real rectangle, so ; and if . Let , and let . Let be the largest index in with . Bars are higher than , so by Lemma 3. Bars are at least , so . Line L7 for records . So at the end.
Cost. Each of the indices is pushed once and popped at most once, so the loop of line L4 runs at most times in all, and the algorithm stops after steps.