Files
rose-ash/lib/ocaml/baseline/gas_station.ml
giles fed07059a3
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 23s
ocaml: phase 5.1 gas_station.ml baseline (circular tour start = 3)
Classic O(n) greedy gas-station algorithm:

  walk once, tracking
    total = sum of (gas[i] - cost[i])  -- if negative, no answer
    curr  = running tank since start   -- on negative, advance
                                          start past i+1 and reset

  if total < 0 then -1 else start

For gas = [1;2;3;4;5], cost = [3;4;5;1;2], unique start = 3.

Tests `total` + `curr` parallel accumulators, reset-on-failure
pattern.

202 baseline programs total.
2026-05-11 05:44:38 +00:00

22 lines
451 B
OCaml

let gas_circuit gas cost =
let n = Array.length gas in
let total = ref 0 in
let curr = ref 0 in
let start = ref 0 in
for i = 0 to n - 1 do
let diff = gas.(i) - cost.(i) in
total := !total + diff;
curr := !curr + diff;
if !curr < 0 then begin
start := i + 1;
curr := 0
end
done;
if !total < 0 then -1 else !start
;;
let gas = [| 1; 2; 3; 4; 5 |] in
let cost = [| 3; 4; 5; 1; 2 |] in
gas_circuit gas cost