Which pack size is the best value
The same product sits on the shelf in several pack sizes. A price-comparison badge needs the one with the lowest cost per unit.
- Compare price per unit, not sticker price.
- Skip any pack claiming zero or fewer units — that is bad data, not a bargain.
- On a tie, the larger pack wins.
- With nothing worth comparing, return null.
cheapestPack(packs: list<Pack>) → string?
Java needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
String cheapestPack(List<Pack> packs) {
}
Worked examples
| Call | Result |
|---|---|
cheapestPack(Main.<Pack>ls(new Pack("single", 1, 300), new Pack("six", 6, 1500), new Pack("crate", 24, 6200))) | "six" |
cheapestPack(Main.<Pack>ls(new Pack("a", 2, 200), new Pack("b", 4, 400))) | "b" |
cheapestPack(Main.<Pack>ls(new Pack("broken", 0, 100), new Pack("ok", 3, 900))) | "ok" |
cheapestPack(Main.<Pack>ls()) | (String) null |
Hint
Cross-multiply instead of dividing: a.price * b.units against b.price * a.units keeps it in integers.
Reference solution in Java
String cheapestPack(List<Pack> packs) {
Pack best = null;
for (Pack p : packs) {
if (p.units <= 0) continue;
if (best == null) { best = p; continue; }
long a = (long) p.price * best.units, b = (long) best.price * p.units;
if (a < b || (a == b && p.units > best.units)) best = p;
}
return best == null ? null : best.label;
}