|
| 1 | +// PS: |
| 2 | +// Given an array consisting of the cost of toys. |
| 3 | +// Given an integer K depicting the amount of money available to purchase toys. |
| 4 | +// Write a program to find the maximum number of toys one can buy with the amount K. |
| 5 | + |
| 6 | +#include <cmath> |
| 7 | +#include <cstdio> |
| 8 | +#include <vector> |
| 9 | +#include <iostream> |
| 10 | +#include <algorithm> |
| 11 | +#include <bits/stdc++.h> |
| 12 | +using namespace std; |
| 13 | +#define ll long long int |
| 14 | +#define lt long long |
| 15 | +#define pi (3.141592653589) |
| 16 | +#define mod 1000000007 |
| 17 | + |
| 18 | +#define tc \ |
| 19 | + int t; \ |
| 20 | + cin >> t; \ |
| 21 | + while (t--) |
| 22 | + |
| 23 | +#define lull NULL |
| 24 | + |
| 25 | +#define float double |
| 26 | + |
| 27 | +#define pb push_back |
| 28 | + |
| 29 | +#define mp make_pair |
| 30 | + |
| 31 | +#define ff first |
| 32 | + |
| 33 | +#define ss second |
| 34 | + |
| 35 | +#define all(c) c.begin(), c.end() |
| 36 | + |
| 37 | +#define min3(a, b, c) min(c, min(a, b)) |
| 38 | + |
| 39 | +#define min4(a, b, c, d) min(d, min(c, min(a, b))) |
| 40 | + |
| 41 | +#define fir(i, n) for (int i = n - 1; i >= 0; i--) |
| 42 | + |
| 43 | +#define fi(i, n) for (int i = 0; i < n; i++) |
| 44 | +#define fin(j, n) for (int i = j; i <= n; i++) |
| 45 | + |
| 46 | +#define fast ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr); |
| 47 | + |
| 48 | +// This functions returns the required number of toys |
| 49 | +int maximum_toys(vector<int> &cost, int N, int K) |
| 50 | +{ |
| 51 | + int count = 0, sum = 0; |
| 52 | + |
| 53 | + // sort the cost array |
| 54 | + sort(cost.begin(), cost.end()); |
| 55 | + for (int i = 0; i < N; i++) |
| 56 | + { |
| 57 | + |
| 58 | + // Check if we can buy ith toy or not |
| 59 | + if (sum + cost[i] <= K) |
| 60 | + { |
| 61 | + sum = sum + cost[i]; |
| 62 | + // Increment count |
| 63 | + count++; |
| 64 | + } |
| 65 | + } |
| 66 | + return count; |
| 67 | +} |
| 68 | + |
| 69 | +int main() |
| 70 | +{ |
| 71 | + int k, n; |
| 72 | + cin >> n >> k; |
| 73 | + |
| 74 | + vector<int> arr(n); |
| 75 | + fi(i, n) |
| 76 | + { |
| 77 | + cin >> arr[i]; |
| 78 | + } |
| 79 | + cout << maximum_toys(arr, n, k) << endl; |
| 80 | + return 0; |
| 81 | +} |
0 commit comments