ocaml: phase 5.1 kadane.ml baseline (max subarray sum = 6)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 24s
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 24s
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.
This commit is contained in:
@@ -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,
|
||||
|
||||
12
lib/ocaml/baseline/kadane.ml
Normal file
12
lib/ocaml/baseline/kadane.ml
Normal file
@@ -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]
|
||||
Reference in New Issue
Block a user