Given an array of integers costs where costs[i] is the cost of the i-th item, and an integer budget that is the total available budget, find the maximum number of consecutive items you can acquire without exceeding the budget.
You must select a contiguous subarray of items. The total cost of the selected items must be less than or equal to budget. Return the length of the longest such subarray.
Function Signature
def max_consecutive_items(costs: list[int], budget: int) -> int:
Rules
-
A selection is a contiguous block
costs[i..j]
. Skipping an item inside the block is not allowed.
-
A total exactly equal to
budget
is allowed.
-
If every single item costs more than
budget
, return 0.
Constraints
-
1 <= costs.length <= 10^5
-
1 <= costs[i] <= 10^4
-
1 <= budget <= 10^9
Examples
Input: costs = [3,1,2,5,4,2], budget = 10
Output: 3
Every block of four items costs more than 10: [3,1,2,5] costs 11, [1,2,5,4] costs 12 and [2,5,4,2] costs 13. The blocks [3,1,2] (cost 6) and [1,2,5] (cost 8) fit, so the answer is 3.
Input: costs = [5,5,5,5], budget = 12
Output: 2
Two items cost 10, which fits. Three items cost 15, which exceeds 12.
Input: costs = [12,15], budget = 10
Output: 0
Each item alone costs more than the budget, so no block fits.