Approach

The problem is to seletc at most 2 datas, and we can seperate this into two problems: select 1 and select 2.

For selcet 1, it is really simple, we just get the max capcacity that the cost is smaller then budget.

For select 2, we use two pointer to do this in linear time. We sort the data by cost and then try to match from the end.

Let r=n-1, and we find the l that the total cost is still smaller then budget (notice that after this we should move l one step backward, get a WA on this once … ), then when we do --r, we only need to move from the original l pointer to get the next largest cost. For each largest cost l for each r, we can get the get capacity by maintaining the best capacity first.

Code

class Solution {
public:
    int maxCapacity(vector<int>& costs, vector<int>& capacity, int budget) {
        int n = costs.size();
        int maxCap = 0;
        for(int i = 0 ; i < n ; ++i) {
            if(costs[i] >= budget) continue;
            maxCap = max(maxCap, capacity[i]);
        }

        vector<pair<int,int>> v; // cost, cap
        v.reserve(n);
        for(int i = 0 ; i < n ; ++i) {
            v.push_back({costs[i], capacity[i]});
        }

        // sort by cost.
        sort(v.begin(), v.end(), [](auto& a, auto& b){
            if(a.first < b.first) return true;
            if(a.first > b.first) return false;
            if(a.second < b.second) return true;
            return false;
        });

        // maintain max cap per index.
        vector<int> maxCapVec(n);
        int curMax = 0;
        for(int i = 0 ; i < n ; ++i) {
            curMax = max(curMax, v[i].second);
            maxCapVec[i] = curMax;
        }
            
        int l = 0;
        for(int r = n-1; r >= 1 ; --r) {
            if(l > r-1) {
                maxCap = max(maxCap, v[r].second + maxCapVec[r-1]);
                l = r-1;
                continue;
            }
            while(l <= r-1 && v[l].first + v[r].first < budget) {
                maxCap = max(maxCap, v[r].second + maxCapVec[l]);
                ++l;
            }
            if(l > 0) --l;
        }
        return maxCap;
    }
};