algoblazerEarly Access
LearnProblemsLeaderboard
Log inSign up

All problems

‹ Back to map
1 shown · 0/261 solved

Farthest Reach Within Budget

SilverCommunity Beta
Asked atAdobe
Solve problem →
2000ms256MBAdded Aug 3, 2026Binary Search

You are given an integer array costs, where visiting index i costs costs[i], and an array queries where queries[k] = [start, budget].

For each query you begin at index start and move forward one index at a time, paying the cost of every index you visit, including start itself. You stop before the first index you can no longer afford.

Return an array with one answer per query: the largest index j such that costs[start] + costs[start+1] + ... + costs[j] <= budget. If even costs[start] exceeds the budget, the answer for that query is -1.

Examples

Example 1

Input: costs = [3,1,4,2,5], queries = [[1,7],[0,3],[2,3]]
Output: [3,0,-1]
Explanation: From index 1 with budget 7: 1 + 4 + 2 = 7 reaches index 3 (adding costs[4] = 5 would exceed 7). From index 0 with budget 3: costs[0] = 3 fits exactly but 3 + 1 = 4 does not, so the answer is 0. From index 2 with budget 3: costs[2] = 4 > 3, so the answer is -1.
Read full statement →

Constraints

  • 1≤1 \leq1≤ costs.length ≤105\leq 10^5≤105
  • 1≤1 \leq1≤ costs[i] ≤104\leq 10^4≤104
  • 1≤1 \leq1≤ queries.length ≤5⋅104\leq 5 \cdot 10^4≤5⋅104
  • queries[k] =[start,budget]= [start, budget]=[start,budget] with 0≤start<0 \leq start <0≤start< costs.length and 0≤budget≤1090 \leq budget \leq 10^90≤budget≤109

Details

Solved by10 people
Time limit2000ms
Memory256MB
AddedAug 3, 20265 weeks ago
Binary Search

More like this