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.
Can you guys make a review on my solution . I tried coding up the solution using upper bound but my solution did not pass ,plz tell me where my code goes wrong.
Yeah this also does exactly what our intended solution does. Ultimately we need to find out the second choice for candy out of all available options, which we can easily do by range max query after finding the range.
And yeah this is kinda overkill for the problem, but this idea is simple to implement as segment tree template can be used to quickly code.
I had also implemented sort of same idea constructed prefix array for sweetness after sorting vector of ({price,sweetness}) and binary search for ith candies which seems fine but don’t know where does it go wrong. Here is my solution O(nlogn) giving wrong answer plz help on that @vichitrand@thunderhashira .
This is wrong because you are just considering the candy at index j after upper bound on price. But there maybe many candies whose price <= D-P where P is price of first candy. So you need to take maximum sweetness candy among them.
You ignore the fact that there are many possible options for second candy.
Your code has same bug as that of mine your logic is perfectly fine. You just take j=min(j,i-1) why ? There is simple explanation to this as you have store the maximum sweetness of candies for range in sweewtness ~~prefix array if your j ~index surpasses the ith~ index it may happen that you consider the ithcandies twice which is wrong according to problem. here is your debug~ code
I tried sorting the pairs in descending order of sweetness/price and then choosing most suitable 2 elements. I used an approach similar to fractional knapsack.
It clears the given test cases but is showing WA after submission. This is my solution, please tell me where am I wrong.
Can someone review my solution? I tried to use binary search to get the max position of the sweetness and then used a sparse table for max. But I am getting TLE on the 2nd task
#define ll long long #define fastio ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL) #define pb push_back #define ff first #define ss second #define endl ‘\n’