Files
rose-ash/lib/ocaml/baseline/daily_temperatures.ml
giles 8ab2f80615
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 24s
ocaml: phase 5.1 daily_temperatures.ml baseline (sum of waits = 10)
Monotonic decreasing stack — for each day i, pop entries from
the stack whose temperature is strictly less than today's; their
answer is (i - popped_index).

  temps  = [73; 74; 75; 71; 69; 72; 76; 73]
  answer = [ 1;  1;  4;  2;  1;  1;  0;  0]
  sum    = 10

Complementary to next_greater.ml (iter 256) — same monotonic-stack
skeleton but stores the distance to the next greater element
rather than its value.

Tests `match !stack with | top :: rest when …` pattern with
guard inside a while-cont-flag loop.

198 baseline programs total.
2026-05-11 05:04:37 +00:00

25 lines
541 B
OCaml

let daily_temperatures temps =
let n = Array.length temps in
let answer = Array.make n 0 in
let stack = ref [] in
for i = 0 to n - 1 do
let cont = ref true in
while !cont do
match !stack with
| top :: rest when temps.(top) < temps.(i) ->
answer.(top) <- i - top;
stack := rest
| _ -> cont := false
done;
stack := i :: !stack
done;
let sum = ref 0 in
for i = 0 to n - 1 do
sum := !sum + answer.(i)
done;
!sum
;;
daily_temperatures [| 73; 74; 75; 71; 69; 72; 76; 73 |]