• + 0 comments

    C++ variation of your idea. O(n log(n)) time complexity

    int getMoneySpent(vector<int> keyboards, vector<int> drives, int b) {
        std::sort(keyboards.begin(), keyboards.end());
        std::sort(drives.begin(), drives.end());
        int maxSum = -1;
        for(int j = drives.size() - 1, i = 0; i < keyboards.size() && j >= 0;) {
            const int sum = keyboards[i] + drives[j];
            if (sum <= b) {
                if (sum > maxSum)
                    maxSum = sum;
                i++;
            } else {
                j--;
            }
        }
        return maxSum;
    }