Example:
Given a list of random numbers [1,5,1,1,3,10,5,4,2,1], the test element N=10 at index 5 and a MIN=20.
The shortest sublist including 10 with a total>20 is obviously the list [3,10,5,4] with a total=22 and a size=4.
Problem:
What is an algorithm to find such a sublist in an efficient way?
Edit:
-
There might be different sublists that satisfy the condition “shortest”.
[10,5,4,2]is as short as[3,10,5,4]and a valid result, too. -
A “Sublist” in this question is a consecutive block of items of the original list.
[5,10,5,4]is not a valid sublist (I would call it instead a subset).
The following algorithm should be O(n):
Starting with test element go add elements to the left until sum>=min. This gives a first guess on the sublist length l (starting at index i). No increase start index i of sublist of length l with each step (until you reach your test element) and with each step test if you can shorten the sublist by one (on the right, i.e. decrease length l) without becoming smaller than min.
Take care of edge-cases: sum to the left is not big enough or total sum is not big enough.