Files
rose-ash/lib/ocaml/baseline/stock_two.ml
giles 97a29c6bac
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 23s
ocaml: phase 5.1 stock_two.ml baseline (best of 2 transactions = 6)
Two-pass partition DP for max profit with at most 2 transactions:

  left[i]  = max single-trans profit in prices[0..i]
              (forward scan tracking running min)
  right[i] = max single-trans profit in prices[i..n-1]
              (backward scan tracking running max)
  answer   = max over i of (left[i] + right[i])

For [3; 3; 5; 0; 0; 3; 1; 4]:
  optimal partition i = 2:
    left[2]  = sell@5 after buy@3            = 2
    right[2] = sell@4 after buy@0 in [2..7]  = 4
                                       total = 6

Tests parallel forward + backward passes on parallel DP arrays,
mixed ref + array state, for downto + for ascending scans on
the same data.

190 baseline programs total.
2026-05-11 03:44:40 +00:00

30 lines
829 B
OCaml

let max_profit_two prices =
let n = Array.length prices in
if n < 2 then 0
else begin
let left = Array.make n 0 in
let min_p = ref prices.(0) in
for i = 1 to n - 1 do
if prices.(i) < !min_p then min_p := prices.(i);
let p = prices.(i) - !min_p in
left.(i) <- if p > left.(i - 1) then p else left.(i - 1)
done;
let right = Array.make n 0 in
let max_p = ref prices.(n - 1) in
for i = n - 2 downto 0 do
if prices.(i) > !max_p then max_p := prices.(i);
let p = !max_p - prices.(i) in
right.(i) <- if p > right.(i + 1) then p else right.(i + 1)
done;
let best = ref 0 in
for i = 0 to n - 1 do
let total = left.(i) + right.(i) in
if total > !best then best := total
done;
!best
end
;;
max_profit_two [| 3; 3; 5; 0; 0; 3; 1; 4 |]