As reported: Google L3 onsite, round 2, first problem (2025): a nephew gives his uncle a list of gifts, each with the day it is available and its price; the uncle saves 1 dollar per day, can buy a gift only on its day, and a gift that is skipped cannot be bought later. Maximise the number of gifts bought. Solved with a priority queue; the interviewer hinted at DP. Also asked in a Google L4 onsite round 2 (2025) with gifts given as
(day, cost):(3,2) (5,4) (6,3)→2;(1,2) (3,2) (5,3) (6,2) (7,2)→3;(1,1) (50,40) (51,20) (52,20)→3, where buying greedily on day 50 is wrong.
The uncle saves exactly 1 dollar per day, so by day d he has saved d dollars in total, minus whatever he has already spent. Gift i is available only on day day_i and costs price_i; he can buy it on that day if his savings cover the price. Return the maximum number of gifts he can buy.
Example
gifts (day price) = [(3,4), (4,2), (6,4), (10,5)]
-> 2
buy (4,2) on day 4 (saved 4), then (6,4) on day 6 (saved 6 − 2 = 4);
on day 10 only 4 dollars are left for a gift of 5.
Buying (6,4) and (10,5) instead also gives 2.
gifts = [(1,1), (2,1), (3,1)] -> 3
gifts = [(2,3)] -> 0
Clarifications
- Savings start on day 1: on day
d, before any purchase,ddollars have been saved in total. - Several gifts may share a day; he may buy as many of them as his savings allow.
- Gifts are given in any order.
Constraints: 1 ≤ n ≤ 10^5; 1 ≤ day_i, price_i ≤ 10^9.
Code runner format: the first line is n, then n lines day price. Implement maxGifts(gifts); the harness prints the result.