From b3d5da53610cfec61aec473aeb08d22d5402d20e Mon Sep 17 00:00:00 2001 From: giles Date: Sat, 9 May 2026 10:07:12 +0000 Subject: [PATCH] ocaml: phase 5.1 kadane.ml baseline (max subarray sum = 6) Kadane's algorithm in O(n): let max_subarray xs = let max_so_far = ref min_int in let cur = ref 0 in List.iter (fun x -> cur := max x (!cur + x); max_so_far := max !max_so_far !cur ) xs; !max_so_far For [-2;1;-3;4;-1;2;1;-5;4] the optimal subarray is [4;-1;2;1] = 6. Exercises min_int (iter 94), max as global, ref / ! / :=, and List.iter with two side-effecting steps in one closure body. 46 baseline programs total. --- lib/ocaml/baseline/expected.json | 1 + lib/ocaml/baseline/kadane.ml | 12 ++++++++++++ plans/ocaml-on-sx.md | 5 +++++ 3 files changed, 18 insertions(+) create mode 100644 lib/ocaml/baseline/kadane.ml diff --git a/lib/ocaml/baseline/expected.json b/lib/ocaml/baseline/expected.json index f0724929..5e4f9195 100644 --- a/lib/ocaml/baseline/expected.json +++ b/lib/ocaml/baseline/expected.json @@ -21,6 +21,7 @@ "fizzbuzz.ml": 57, "list_ops.ml": 30, "json_pretty.ml": 24, + "kadane.ml": 6, "lambda_calc.ml": 7, "levenshtein.ml": 11, "memo_fib.ml": 75025, diff --git a/lib/ocaml/baseline/kadane.ml b/lib/ocaml/baseline/kadane.ml new file mode 100644 index 00000000..49774818 --- /dev/null +++ b/lib/ocaml/baseline/kadane.ml @@ -0,0 +1,12 @@ +let max_subarray xs = + let max_so_far = ref min_int in + let cur = ref 0 in + List.iter (fun x -> + cur := max x (!cur + x); + max_so_far := max !max_so_far !cur + ) xs; + !max_so_far + +;; + +max_subarray [-2; 1; -3; 4; -1; 2; 1; -5; 4] diff --git a/plans/ocaml-on-sx.md b/plans/ocaml-on-sx.md index e263bf85..aabe7b2e 100644 --- a/plans/ocaml-on-sx.md +++ b/plans/ocaml-on-sx.md @@ -407,6 +407,11 @@ _Newest first._ binary search tree (`type 'a tree = Leaf | Node of 'a * 'a tree * 'a tree`) with insert + in-order traversal. Tests parametric ADT, recursive match, List.append, List.fold_left. +- 2026-05-09 Phase 5.1 — kadane.ml baseline (Kadane's max subarray + sum = 6). Classic O(n) algorithm using two refs and `max`. For + [-2;1;-3;4;-1;2;1;-5;4] the optimal subarray is [4;-1;2;1] = 6. + Exercises `min_int`, `max`, ref/!/:=, and List.iter with multiple + side-effecting steps in one closure body. 46 baseline programs total. - 2026-05-09 Phase 5.1 — pascal.ml baseline (Pascal's triangle row 10 middle = C(10, 5) = 252). next_row prepends 1, walks adjacent pairs (x, y) emitting x+y, appends a final 1. row n iterates