#P8444. Maximizing Acquired Items via Exchanges
Maximizing Acquired Items via Exchanges
Maximizing Acquired Items via Exchanges
You are given n items available for purchase; the price of the i-th item is \(a_i\). You are also given a positive integer \(w\), representing the amount of money you have. You are allowed to buy exactly one item initially (its price must not exceed \(w\)).
After the purchase, the shopkeeper permits you to exchange a non-empty subset of the items you currently own for some of the remaining items, with the restriction that the total value of the items you receive is at most equal to the total value of the items you trade in. (You may also choose not to perform any exchange.)
Your goal is to maximize the number of items you ultimately possess. Note that you cannot use an empty set to exchange for other items.
Hint: Observe that every exchange is value‐preserving or value‐reducing. Therefore, if you initially purchase an item with value \(p\), then throughout all exchanges the total value of the items you hold is always at most \(p\). This means that you can only accumulate items whose individual prices are no greater than \(p\). By selecting the cheapest items available you can maximize their count, subject to the invariant that their total sum does not exceed \(p\).
inputFormat
The first line contains two integers \(n\) and \(w\) (\(1 \le n \le 10^5\), \(1 \le w \le 10^9\)), representing the number of items and the amount of money you have.
The second line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \le a_i \le 10^9\)), where \(a_i\) denotes the price of the i-th item.
outputFormat
Output a single integer, the maximum number of items you can obtain following the rules above.
sample
4 5
3 5 2 6
2
</p>