ocaml: phase 5.1 histogram_area.ml baseline (largest rectangle = 10)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 22s
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 22s
Linear-time stack algorithm for largest rectangle in histogram:
for i = 0 to n do
let h = if i = n then 0 else heights.(i) in
while top-of-stack's height > h do
pop the top, compute its max-width rectangle:
width = (no-stack ? i : i - prev_top - 1)
area = height * width
update best
done;
if i < n then push i
done
Sentinel pass at i=n with h=0 flushes the remaining stack.
For [2; 1; 5; 6; 2; 3], bars at indices 2 (h=5) and 3 (h=6) form
a width-2 rectangle of height 5 = 10.
Tests guarded patterns with `when` inside while-cont-flag, nested
`match !stack with | [] -> i | t :: _ -> i - t - 1` for width
computation.
178 baseline programs total.
This commit is contained in:
@@ -75,6 +75,7 @@
|
||||
"hamming.ml": 4,
|
||||
"hanoi.ml": 1023,
|
||||
"hist.ml": 75,
|
||||
"histogram_area.ml": 10,
|
||||
"huffman.ml": 224,
|
||||
"int_sqrt.ml": 1027,
|
||||
"is_prime.ml": 25,
|
||||
|
||||
27
lib/ocaml/baseline/histogram_area.ml
Normal file
27
lib/ocaml/baseline/histogram_area.ml
Normal file
@@ -0,0 +1,27 @@
|
||||
let max_rect heights =
|
||||
let n = Array.length heights in
|
||||
let stack = ref [] in
|
||||
let best = ref 0 in
|
||||
for i = 0 to n do
|
||||
let h = if i = n then 0 else heights.(i) in
|
||||
let cont = ref true in
|
||||
while !cont do
|
||||
match !stack with
|
||||
| top :: rest when heights.(top) > h ->
|
||||
let height = heights.(top) in
|
||||
stack := rest;
|
||||
let width = match !stack with
|
||||
| [] -> i
|
||||
| t :: _ -> i - t - 1
|
||||
in
|
||||
let area = height * width in
|
||||
if area > !best then best := area
|
||||
| _ -> cont := false
|
||||
done;
|
||||
if i < n then stack := i :: !stack
|
||||
done;
|
||||
!best
|
||||
|
||||
;;
|
||||
|
||||
max_rect [| 2; 1; 5; 6; 2; 3 |]
|
||||
Reference in New Issue
Block a user