Pallet pair under limit
Choose two different pallet positions whose combined weights do not exceed a limit. Prefer the greatest feasible total. If several pairs achieve that total, print the lexicographically smallest pair of weights in ascending order. Print NONE if no pair fits. Two equal weights need two separate positions.
Input
First line limit; second line 2 to 100 non-negative integer pallet weights.
Output
weight1 weight2 total, or NONE.
Example 1
Input
10 6 4 7 3 5 5
Output
3 7 10
Several pairs reach ten, including 6+4, 7+3 and 5+5; the ascending pair 3,7 wins the value tie-break.
Constraints
- There are 2 to 100 pallet positions.
- Pallet weights and the limit are non-negative safe integers.
Hints
Hint 1 of 2
Compare indices i < j rather than values alone.
Hint 2 of 2
A better pair has a higher total; on a tie compare its ascending weights.
Solution
Show a reference solution and explanation
const limit = Number(readline());
const weights = readline().split(' ').map(Number);
let best = null;
for (let i = 0; i < weights.length; i++) {
for (let j = i + 1; j < weights.length; j++) {
const pair = [Math.min(weights[i], weights[j]), Math.max(weights[i], weights[j])];
const total = pair[0] + pair[1];
if (total > limit) continue;
if (!best || total > best.total || (total === best.total && (pair[0] < best.a || (pair[0] === best.a && pair[1] < best.b)))) best = { a: pair[0], b: pair[1], total };
}
}
console.log(best ? `${best.a} ${best.b} ${best.total}` : 'NONE');
Why it works
Two nested index loops enforce distinct pallets, including the case of repeated weights. Candidate pairs are normalized to ascending values before comparison. Tracking both the total and the value pair makes the requested tie-break explicit and testable.
Lesson for this exercise: JavaScript Arrays: Creating, Indexing and Changing Lists