Maximise the number of toys that can be purchased with amount K in C++

C++Server Side ProgrammingProgramming

We are given with the prices of toys in the form of an array and an amount K in hand. The goal is to purchase the maximum no. of toys with that amount. Each element of the array is a price of a single toy, so no. of toys is no. of elements. We will sort the array of prices in ascending order so that maximum toys of less prices can be purchased first followed by costly toys.

Input

toyprices[]= { 10, 20, 12, 15, 50, 30 } K=50

Output

Maximum no. of toys that can be purchased : 3

Explanation − Sorting prices of toys in ascending order − { 10, 12, 15, 20, 30 , 50 }

Take first toy: K=50, count=1, leftover K =40 ( 50-10 )
Take second toy: K=40, count=2, leftover K =28 ( 40-12 )
Take third toy: K=28, count=13, leftover K =13 ( 28-15 )
Now K< price of next toy 20 so count=3

Input

toyprices[]= { 50,40,30,20,10 } K=25

Output

Maximum no. of toys that can be purchased : 1

Explanation − 25>10,20 but you can take only one of them as 10+20=30. Maximum count=1

Approach used in the below program is as follows

  • The integer array toyprice[] stores the prices of toys.

  • Function maxToys( int price[], int N, int K ) takes the prices array, its length and amount

  • toycount is used to store the no. of toys that can be purchased, initially 0.

  • Variable spent is used to check how much money is spent from K.

  • Sort the array price[] in ascending order using sort(price, price + N);

  • Start traversing the array price[] from least price, price[0] till highest.

  • Keep adding the price of the toy in spent and check if <=K, if yes increase toycount. Which means this toy can be taken. Update spent=spent+price[i].

  • At last toycount has number of toys that can be purchased.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int maxToys(int price[], int N, int K){
   int toycount = 0;
   int spent = 0; //money spent upto K only
   // sort the prices so that minium prices are first
   sort(price, price + N);
   for (int i = 0; i < N; i++) {
      if (spent + price[i] <= K){
         spent = spent + price[i];
         toycount++;
      } else
         break; //as array is sorted
   }
   return toycount;
}
int main(){
   int budget = 100;
   int toyprice[] = { 10, 120, 50, 11, 20, 100, 10, 90, 12, 15 };
   int N = 10;
   cout <<"Maximum no. of toys that can be purchased : "<< maxToys(toyprice, N, budget) ;
   return 0;
}

Output

Maximum no. of toys that can be purchased : 6
raja
Published on 03-Aug-2020 10:10:18

Advertisements