Files
rose-ash/lib/ocaml/baseline/max_product3.ml
giles c8206e718a
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 22s
ocaml: phase 5.1 max_product3.ml baseline (max product of 3, with negatives -> 300)
Sort, then compare two candidates:
  p1 = product of three largest values
  p2 = product of two smallest (potentially negative) values and the largest

For [-10;-10;1;3;2]:
  sorted    = [-10;-10;1;2;3]
  p1        = 3 * 2 * 1                = 6
  p2        = (-10) * (-10) * 3        = 300
  max       = 300

Tests List.sort + Array.of_list + arr.(n-i) end-walk + candidate-pick
via if-then-else.

104 baseline programs total.
2026-05-09 20:46:42 +00:00

12 lines
288 B
OCaml

let max_prod3 xs =
let sorted = List.sort compare xs in
let arr = Array.of_list sorted in
let n = Array.length arr in
let p1 = arr.(n - 1) * arr.(n - 2) * arr.(n - 3) in
let p2 = arr.(0) * arr.(1) * arr.(n - 1) in
if p1 > p2 then p1 else p2
;;
max_prod3 [-10; -10; 1; 3; 2]