C++ program to find maximum how many chocolates we can buy with at most k rupees


Suppose we have an array A with n elements, and other values l, r and k are there. Amal wants to buy chocolates and he will not buy too expensive chocolates, and not also too cheap chocolates. In the store, there are n different chocolate bars and the prices are represented in A. A chocolate bar is too expensive if its price is larger than r and too cheap if its price is less than l. He wants to spend at most k rupees. We have to find the maximum amount of chocolates he can buy.

So, if the input is like A = [1, 2, 3, 4, 5, 6]; l = 3; r = 5; k = 10, then the output will be 2, because he can buy chocolates worth rupees 3 and 4 by 7 rupees.

Steps

To solve this, we will follow these steps −

n := size of A
ans := 0
sort the array A
for initialize i := 0, when i < n, update (increase i by 1), do:
   if A[i] > k, then:
      Come out from the loop
   if A[i] >= l and A[i] <= r, then:
      k := k - A[i]
      (increase ans by 1)
return ans

Example

Let us see the following implementation to get better understanding −

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

int solve(vector<int> A, int l, int r, int k) {
   int n = A.size();
   int ans = 0;
   sort(A.begin(), A.end());
   for (int i = 0; i < n; ++i) {
      if (A[i] > k)
         break;
      if (A[i] >= l && A[i] <= r) {
         k -= A[i];
         ++ans;
      }
   }
   return ans;
}
int main() {
   vector<int> A = { 1, 2, 3, 4, 5, 6 };
   int l = 3;
   int r = 5;
   int k = 10;
   cout << solve(A, l, r, k) << endl;
}

Input

{ 1, 2, 3, 4, 5, 6 }, 3, 5, 10

Output

2

Updated on: 03-Mar-2022

354 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements