CP: Most items for the budget

A shop has n items with different prices. You have a budget B and want to buy as many different items as possible, at most one of each.

What to build

Sort the prices from smallest to largest. Buy items in that order while the next price still fits in what is left of the budget, and print how many you bought.

Requirements

  • Sort the prices first
  • Stop at the first item that does not fit
  • Use long long

Input

The first line has n and B. The second line has n prices.

Output

The number of items bought.

Constraints

1 ≤ n ≤ 100,000. Prices are from 1 to 10⁹. B is up to 10¹⁵.

Example

Input:

5 10
4 1 7 2 3

Output:

4

Why it works

Swapping any bought item for a cheaper unbought one never costs more, so the cheapest items are always the best choice. Once the next cheapest does not fit, no later item can, since they cost at least as much.

Examples

Example 1 · Input
5 10
4 1 7 2 3
Expected output
4
Example 2 · Input
3 1
5 6 7
Expected output
0

Hints

Hint 1

sort(a.begin(), a.end());

Hint 2

Loop through the sorted prices, subtracting each price from B while it still fits.

Hint 3

Break at the first price larger than what is left.

Solution

Show one correct solution (try it yourself first)
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n;
    long long B;
    cin >> n >> B;
    vector<long long> a(n);
    for (auto& x : a) cin >> x;
    sort(a.begin(), a.end());
    int bought = 0;
    for (int i = 0; i < n; i++) {
        if (a[i] > B) break;
        B -= a[i];
        bought++;
    }
    cout << bought << "\n";
    return 0;
}

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Sorting first, then greedy →