ocaml: phase 5.1 count_subarrays_k.ml baseline (sum-k subarrays = 7)
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
Count contiguous subarrays summing to a target k using a prefix
sum table:
prefix[i+1] = prefix[i] + arr[i]
count = |{ (i, j) : 0 <= i < j <= n, prefix[j] - prefix[i] = k }|
For arr = [1; 1; 1; 2; -1; 3; 1; -2; 4] and k = 3, the seven
witnesses are:
[1, 1, 1] (0..2)
[1, 1, 2, -1] (1..4)
[1, 2] (2..3)
[2, -1, 3, 1, -2] (3..7)
[-1, 3, 1] (4..6)
[3] (5..5)
[1, -2, 4] (6..8)
Negative-valued arrays exercise mixed-sign integer arithmetic.
186 baseline programs total.
This commit is contained in:
16
lib/ocaml/baseline/count_subarrays_k.ml
Normal file
16
lib/ocaml/baseline/count_subarrays_k.ml
Normal file
@@ -0,0 +1,16 @@
|
||||
let count_subarr_sum_k arr k =
|
||||
let n = Array.length arr in
|
||||
let prefix = Array.make (n + 1) 0 in
|
||||
for i = 0 to n - 1 do
|
||||
prefix.(i + 1) <- prefix.(i) + arr.(i)
|
||||
done;
|
||||
let count = ref 0 in
|
||||
for i = 0 to n - 1 do
|
||||
for j = i + 1 to n do
|
||||
if prefix.(j) - prefix.(i) = k then count := !count + 1
|
||||
done
|
||||
done;
|
||||
!count
|
||||
;;
|
||||
|
||||
count_subarr_sum_k [| 1; 1; 1; 2; -1; 3; 1; -2; 4 |] 3
|
||||
@@ -32,6 +32,7 @@
|
||||
"coin_min.ml": 6,
|
||||
"count_change.ml": 406,
|
||||
"count_inversions.ml": 12,
|
||||
"count_subarrays_k.ml": 7,
|
||||
"csv.ml": 10,
|
||||
"egg_drop.ml": 8,
|
||||
"dijkstra.ml": 7,
|
||||
|
||||
Reference in New Issue
Block a user