Skip to the code
cf.
+25 XP

#101 Count Pairs Under a Budget

medium

A shop's "buy two" promotion only applies when the two items together cost strictly less than budget. Marketing wants to know how many different pairs of items qualify.

Write countPairs(prices, budget) that returns how many index pairs i < j have prices[i] + prices[j] < budget. prices is not sorted, and two items with the same price are still different items.

Example 1

Input: prices = [4,1,3,2], budget = 5
Output: 2

The pairs 1 + 3 and 1 + 2 are under 5. 1 + 4 and 3 + 2 equal 5, which is not strictly less.

Example 2

Input: prices = [10,20,30], budget = 25
Output: 0

Even the two cheapest items, 10 + 20, cost 30.

Constraints

  • 0 <= prices.length <= 100000
  • -10^4 <= prices[i], budget <= 10^4
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).