Electronics Shop

A person wants to determine the most expensive computer keyboard and USB drive that can be purchased with a given budget. Given price-lists for keyboards and USB drives and a budget, find the cost to buy them. If it is not possible to buy both items, return -1.

Example:

Input:  b=10,n=2,m=3,keyboards[]={3,1},drives[]={5,2,8}
Output: 9

Approach

C++

#include <bits/stdc++.h>
using namespace std;

int getMoneySpent(vector<intkeyboards
vector<intdrivesint b)
{
    int n = keyboards.size(), m = drives.size();
    sort(keyboards.begin(), keyboards.end(), greater<int>());
    sort(drives.begin(), drives.end());
    int res = -1;
    for (int i = 0j = 0i < ni++)
    {
        for (; j < mj++)
        {
            if (keyboards[i] + drives[j] > b)
                break;
            if (keyboards[i] + drives[j] > res)
                res = keyboards[i] + drives[j];
        }
    }
    return res;
}
int main()
{
    int b = 10n = 2m = 3;
    vector<intkeyboards = {31};
    vector<intdrives = {528};

    cout << getMoneySpent(keyboardsdrivesb);
    return 0;
}


No comments:

Post a Comment