changeset 29:af82fbc3d6c0

subarray with sum k
author Lewin Bormann <lbo@spheniscida.de>
date Sat, 04 Mar 2023 17:00:38 +0100
parents 743af1962848
children 9b19f04208e4
files julia/arrays.jl
diffstat 1 files changed, 18 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/julia/arrays.jl	Sat Mar 04 16:39:37 2023 +0100
+++ b/julia/arrays.jl	Sat Mar 04 17:00:38 2023 +0100
@@ -471,3 +471,21 @@
         quickselect(a, k, pivix+1, j)
     end
 end
+
+# Naive
+function subarrays_with_sum(a::AbstractVector{<:Integer}, s)
+    running_sum = copy(a)
+    for i = 2:length(a)
+        running_sum[i] = running_sum[i-1] + a[i]
+    end
+
+    subarrays = Pair[]
+    for i = 1:length(a)
+        for j = i:length(a)
+            if running_sum[j] - running_sum[i] == s
+                push!(subarrays, i+1 => j)
+            end
+        end
+    end
+    subarrays
+end