tinycodinglm / cp2 /cp-0041.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 15)
b27bfb3 verified
|
Raw History Blame Contribute Delete
3.31 kB
cp-practice-sim trace
System You are a competitive-programming assistant. Deliver correct, complete, runnable solutions that read standard input and write standard output. Give only a concise rationale: approach, correctness idea, and time/space com...

You are a competitive-programming assistant. Deliver correct, complete, runnable solutions that read standard input and write standard output. Give only a concise rationale: approach, correctness idea, and time/space complexity.

User 2026-11-08T14:20:03.537Z

Budget Shopping

Topic: Sorting and greedy | Difficulty: beginner

Problem

A shop sells n items with given prices, one unit of each. You have a budget B. Print the largest number of different items you can buy without spending more than B in total.

Input

The first line contains n and B. The second line contains the n prices.

Output

Print one integer: the maximum number of items.

Constraints

  • 1 <= n <= 2*10^5
  • 1 <= price <= 10^9
  • 0 <= B <= 10^15

Examples

Example 1

Input:

markdown
5 10
4 3 8 1 2

Output:

markdown
4

Note: Prices 1, 2, 3, 4 sum to exactly 10.

Example 2

Input:

markdown
3 1
5 6 7

Output:

markdown
0

Solve this in C++17, Rust, Kotlin, one complete program per language. Include a concise rationale (approach, correctness idea, time/space complexity).

Assistant 2026-11-08T14:20:05.511Z

Approach. Sort the prices ascending and keep buying the cheapest remaining item while it fits in the budget.

Correctness. Any set of k items costs at least the sum of the k cheapest, so if some k items fit, the k cheapest fit too.

Complexity. Time: O(n log n). Space: O(n).

C++17

cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
    int n; long long b;
    scanf("%d %lld", &n, &b);
    vector<long long> p(n);
    for (auto &x : p) scanf("%lld", &x);
    sort(p.begin(), p.end());
    int c = 0;
    for (long long x : p) {
        if (x > b) break;
        b -= x;
        c++;
    }
    printf("%d\n", c);
}

Rust

rust
use std::io::*;
fn main() {
    let mut t = String::new();
    stdin().read_to_string(&mut t).unwrap();
    let mut it = t.split_whitespace().map(|x| x.parse::<i64>().unwrap());
    let n = it.next().unwrap() as usize;
    let mut b = it.next().unwrap();
    let mut p: Vec<i64> = it.take(n).collect();
    p.sort();
    let mut c = 0;
    for x in p {
        if x > b {
            break;
        }
        b -= x;
        c += 1;
    }
    println!("{}", c);
}

Kotlin

kotlin
fun main() {
    val (n, b0) = readLine()!!.trim().split(" ").map { it.toLong() }
    val p = readLine()!!.trim().split(" ").map { it.toLong() }.sorted()
    var b = b0
    var c = 0
    for (x in p) {
        if (x > b) break
        b -= x
        c++
    }
    println(c)
}