Posted on

Description

Submission

class Solution {
public:
    int closestCost(vector<int>& baseCosts, vector<int>& toppingCosts, int target) {
        vector<int> costs = toppingCosts;
        copy(toppingCosts.begin(), toppingCosts.end(), back_inserter(costs));
        int n = costs.size();

        int ret = INT_MAX;
        for(auto base: baseCosts) {
            for(int state = 0; state < (1 << n); ++state) {
                int cur = base;
                for(int i = 0; i < n; ++i) {
                    if((state>>i)&1) cur += costs[i];
                }
                int gap1 = abs(cur - target);
                int gap2 = abs(ret - target);
                if(gap1 < gap2 || (gap1 == gap2 && cur < ret)) ret = cur; 
            }
        }
        return ret;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *