Choose two supplies within budget
A workshop must buy exactly two different supply items. Read the budget and the item prices, then print the largest total price that does not exceed the budget. Print NONE when no pair is affordable. Two equal prices may be used only when they occur at different positions in the list.
Input
First line: N and the budget. Second line: N integer prices.
Output
The best affordable pair total, or NONE if no pair is affordable.
Example 1
Input
5 100 35 60 20 75 40
Output
100
The items priced 60 and 40 use the full budget.
Constraints
- 2 <= N <= 200
- 1 <= each price <= 10000
- 1 <= budget <= 20000
Hints
Hint 1 of 3
Try every pair of positions i and j where i is smaller than j.
Hint 2 of 3
Keep a total only when it is at most the budget.
Hint 3 of 3
Store the largest valid total seen so far; start with no answer rather than zero.
Solution
Show a reference solution and explanation
count, budget = map(int, input().split())
prices = list(map(int, input().split()))
best = None
for i in range(count):
for j in range(i + 1, count):
total = prices[i] + prices[j]
if total <= budget and (best is None or total > best):
best = total
print(best if best is not None else "NONE")
const [count, budget] = readline().split(' ').map(Number);
const prices = readline().split(' ').map(Number);
let best = null;
for (let i = 0; i < count; i++) {
for (let j = i + 1; j < count; j++) {
const total = prices[i] + prices[j];
if (total <= budget && (best === null || total > best)) best = total;
}
}
console.log(best === null ? 'NONE' : best);
Approach
The nested loops visit each pair of distinct positions exactly once. A candidate replaces the current answer only when it is affordable and larger, so the stored value is the best valid total after all pairs have been checked.