Skip to the code
cf.
+10 XP

#158 Items Within Budget

easy

A shopping app has a "Under your budget" filter. Product prices are stored in prices, sorted from cheapest to most expensive, and some products share a price.

Write countAffordable(prices, budget) that returns how many products cost at most budget.

Use binary search rather than checking every price.

Example 1

Input: prices = [5,10,10,25,40], budget = 10
Output: 3

5, 10, and 10 cost at most 10.

Example 2

Input: prices = [5,10,10,25,40], budget = 4
Output: 0

Even the cheapest product costs more than 4.

Constraints

  • 0 <= prices.length <= 100000
  • prices is sorted ascending.
  • 0 <= prices[i], budget <= 10^6
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).