Expand until a constraint is met
Updated
Keep R += 1 and add a[R] to sum until sum ≥ S, or until R cannot grow. Stop at the first moment the constraint holds.
What to focus on
Window constraint: sum ≥ S. Expand only. L is fixed. If sum never reaches S, R ends at n-1 and the constraint is unmet.
Worked examples
hit at last cell
a = [4, 1, 9], S=10, L=0 R=-1- R=0 sum=4 < 10
- R=1 sum=5 < 10
- R=2 sum=14 ≥ 10 stop
Result: L=0 R=2 · sum 14
hit earlier
a = [4, 1, 9, 1], S=5, L=0 R=-1- R=0 sum=4 < 5
- R=1 sum=5 ≥ 5 stop
- do not take index 2
Result: L=0 R=1 · sum 5
never met
a = [7], S=10, L=0 R=-1- R=0 sum=7 < 10
- R cannot grow
Result: L=0 R=0 · unmet
Try it
Write expandUntilSum(a, S). a is an array of positive integers. S is the sum target. L stays 0. R grows. The window includes a[0..R]. Valid means sum ≥ S. Print (L, R), sum, and whether S was met. Return nothing. Stop at the first valid window, or at n-1 if unmet. On [4, 1, 9] S=10; [4, 1, 9, 1] S=5; [1, 2, 3] S=10.
All values are positive integers. S is a positive integer (reachable or not — that is the expand).