← Questions

Max purchases from a sorted price row

0
UberCodingLast asked Mar 2026

A coding interview question asked in Uber's online assessment, last asked Mar 2026. It tests prefix sums, binary-search and greedy.

A market hall has n stalls in a row, numbered 1..n. Stall i sells a single kind of item at price prices[i-1], and the prices are non-decreasing from left to right. A shopper may buy at most one item per stall.

You are given q queries as two arrays of length q, pos and amount. For query j, the shopper starts at stall pos[j] and may visit only stalls pos[j], pos[j]+1, ..., n. Return an array where entry j is the maximum number of items the shopper can buy in query j with total cost at most amount[j].

Implement:

def max_items(prices: list[int], pos: list[int], amount: list[int]) -> list[int]: ...

Constraints

  • 1 <= n, q <= 10^5
  • 0 <= prices[i] <= 10^9, and prices[i] <= prices[i+1]
  • 1 <= pos[j] <= n
  • 0 <= amount[j] <= 10^14

Example 1

prices = [2, 3, 5, 8]
pos    = [1, 2, 4]
amount = [10, 7, 7]
output = [3, 1, 0]

From stall 1 with 10: buy 2 + 3 + 5 = 10, so 3 items. From stall 2 with 7: 3 fits, 3 + 5 does not, so 1. From stall 4 with 7: the only item costs 8, so 0.

Example 2

prices = [1, 1, 1]
pos    = [1, 3]
amount = [100, 0]
output = [3, 0]

A brute-force walk per query is O(n * q). Aim for better.

Clarifying questions

  • Are prices guaranteed non-decreasing, or should the code check?
  • Can prices be 0, so a shopper with 0 can still buy them?
  • Is pos 1-indexed as in the examples?
  • Is the answer only the count, not the items?

What a strong answer covers

  • Because prices are sorted, the cheapest items from pos onward are the consecutive stalls pos, pos+1, ..., so the best purchase is always a prefix of that suffix.
  • Builds prefix sums once; for a query, binary searches the largest k with S[pos - 1 + k] - S[pos - 1] <= amount.
  • O(n + q log n) time, 64-bit sums (up to 10^5 * 10^9).
  • Tests the examples, zero prices, an amount of 0, and an amount large enough for every stall.

Follow-ups

  • Prices are not sorted.
  • The shopper may also go left, or visit only a window [l, r].
  • Prices change between queries.

Where it's asked

  • Uber · Online assessment · Last asked Mar 202690 min · Two problems on a HackerRank-based platform, camera and screen share on · No AI

What it tests

prefix sums · binary-search · greedy

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding