Hackerrank Electronic Shop (C++)

C++ :

int getMoneySpent(vector<int> keyboards, vector<int> drives, int b) {
     * Write your code here.
     int amountSpent = 0;
     vector<int> amounts;

     for(int i = 0; i < keyboards.size(); i++){
         for(int j = 0; j < drives.size(); j++){
             amountSpent = keyboards[i] + drives[j];
             if(amountSpent > b){
                 amountSpent = -1;

     amountSpent = -1;
     for(int k = 0; k < amounts.size(); k++){
         if(amounts[k] > amountSpent){
             amountSpent = amounts[k];

    return amountSpent;


This one is simple. Simply do a nested for loop to loop through all the prices combination of keyboard and drives. Set the amountSpent to -1 if it’s over the budget b, and push every price combination into amounts vector.

The final for loop go through each element in amounts vector, and find the largest possible price combination. amountSpent is initialized to -1 before starting the for loop, so if the entire amounts vector is -1, the returned value will also be -1 (indicating no possible combination).

A way to avoid the final for loop would be to use 2 variables, one to temporary store the next combination, and test against the first. Will attempt to implement in another language during the next run through.

You may also like...

Leave a Reply

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