Given three sorted arrays, I need to pick exactly m elements from them in total with the minimum sum. An additional constraint is that at least r of them must come from the first two. Here is my attempt:
solve :: [Int]->[Int]->[Int]->Int->Int->Int
solve xs ys zs m r = mini [ (xs'!!i) + (ys'!!j) + (zs'!!k) |
i <- [max' (len ys - m) .. len xs],
j <- [max' (r-i) .. len ys],
k <- [max' (m-i-j) .. len zs],
i+j+k == m,
i+j>=r
] where
mini ws = if null ws then (-1) else minimum ws
[xs',ys',zs'] = map (scanl (+) 0) [xs, ys, zs]
max' x = max x 0
len ws = min (length ws) m
(Since the arrays are sorted, I'm considering their prefixes of length i,j,k that satisfy the constraints, and summing them up using scanl.)
My worry is whether this is too inefficient, because of !!. Also, I am wondering if scanl is helping at all. Is this concern valid, and if so how can we fix it?