Longest under budget
Inputs
values is a list of 0 to 14 whole numbers, each from 1 to 9. budget is a whole number from 0 to 40.
Your tasks
- Keep a
leftmarker at 0, a runningsumof 0 andbestof 0. - Use a loop where
rightmoves alongvalues, adding each number tosum. Whilesumis more thanbudget, takevalues[left]away fromsumand moveleftright. - After fixing the window, update
bestwith its lengthright - left + 1. - Complete
longestUnderBudgetso it returnsbest. Return it, do not print it.
Example
With values = [3, 1, 2, 4, 1, 1] and budget = 6, longestUnderBudget returns 3.
Rules
- A stretch is neighbouring numbers.
- If even a single number is more than the budget, the stretch is empty.
Test data
TEST DATA 1: values is [3, 1, 2, 4, 1, 1], budget is 6
TEST DATA 2: values is [], budget is 5
Practice focus
Two pointers and sliding windows: loops that move two positions instead of one. Two pointers and sliding windows turn many quadratic answers into linear ones.