awelgorithms

The valid window is a candidate

Updated

Whenever the window satisfies the constraint, [L,R] is a candidate. Invalid windows are not candidates. You may see many candidates before you pick.

What to focus on

Window constraint: sum ≥ S with S=10 (or 7). A candidate is the current inclusive bounds at a moment sum ≥ S. Recording it does not freeze L and R. The scan continues.

Worked examples

two candidates

a = [4, 1, 9], S=10, R=2
  1. [0,2] sum 14 is a candidate
  2. shrink to [1,2] sum 10 is a candidate
  3. [2,2] sum 9 is not

Result: candidates [0,2] and [1,2]

candidates while shrinking

a = [1, 2, 3, 4], S=7, R=3
  1. [0,3] sum 10
  2. then [1,3] sum 9
  3. then [2,3] sum 7
  4. each ≥ 7 is a candidate

Result: three candidates

one candidate

a = [7], S=7, R=0
  1. [0,0] sum 7 is a candidate
  2. empty after shrink is not

Result: candidate [0,0]

Try it

Write listCandidates(a, S). a is an array of positive integers. S is the sum target. L and R bound a candidate when sum ≥ S. The window includes a[L..R]. Return the list of valid [L, R]. Do not record invalid windows. On [4, 1, 9] S=10; [1, 2, 3, 4] S=7; [7] S=7.

All values are positive integers. S is reachable.