I tried to solve this problem like :- Sort it in the order of `{price,sweetness}`

, and for every index `i`

, finding the upper bound of `D - price[i]`

(the maximum possible pay-able price), lets call that index `j`

.

Now, it reduces down to a range max query on sweetness (because, we’re just finding the maximum possible sweetness you can obtain, given you’ve already picked `i`

) using segment tree in the range `i+1`

to `j`

. But it gave a AC on one task and TLE on another. I don’t find anything wrong in my approach or in my solution here.

Could someone point out where I went wrong? Thanks.

**Edit**: Just fixed it. I added extra conditions where `n==1`

or when `D`

is large enough to be able to buy any two candies. (solution)

So, using a range max query is another valid solution, but maybe an overkill. The editorial solution is clean.