Jack Li's Blog

2300. Successful Pairs of Spells and Potions

class Solution {
public:
    int binarySearch(vector<int>& potions, long long target) {
        int n = potions.size();
        int l = 0;
        int r = n - 1;

        while(l <= r) {
            long long m = l + (r - l) / 2;
            if(potions[m] == target) {
                r = m - 1;
            } else if (potions[m] > target) {
                r = m - 1;
            } else {
                l = m + 1;
            }
        }

        // 1 2  3 4 5
        //   lr
        // r l
        return n - l;
    }
    vector<int> successfulPairs(vector<int>& spells, vector<int>& potions, long long success) {
        vector<int> result;

        sort(potions.begin(), potions.end());

        for(int& spell : spells) {
            long long target = success / spell + (success % spell != 0);
            result.push_back(binarySearch(potions, target));
        }

        return result;
    }
};