Stretches that hit the target
Inputs
values is a list of 0 to 12 whole numbers, each from -4 to 6. target is a whole number from -5 to 10.
Your tasks
- Create a number
countthat starts at 0. - Use an outer loop over each start position. Inside it, keep a running
sumand loop over every end position from the start onward, adding each number. - Add 1 to
countwheneversumequalstarget. - Complete
countStretchesso it returnscount. Return it, do not print it.
Example
With values = [1, 2, 3, -3, 3] and target = 3, countStretches returns 5.
Rules
- A stretch is one or more neighbouring numbers.
- Different positions are different stretches even if the numbers look alike.
Test data
TEST DATA 1: values is [1, 2, 3, -3, 3], target is 3
TEST DATA 2: values is [], target is 0
Practice focus
Prefix sums, counting, binary search, best stretch and sorting, all written as plain loops. This is where loops turn into named algorithms. You have already written the loops.