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?
C# 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
public string CheapestPack(List<Pack> packs) {
}
Worked examples
| Call | Result |
|---|---|
CheapestPack(new List<Pack> { new Pack("single", 1, 300), new Pack("six", 6, 1500), new Pack("crate", 24, 6200) }) | "six" |
CheapestPack(new List<Pack> { new Pack("a", 2, 200), new Pack("b", 4, 400) }) | "b" |
CheapestPack(new List<Pack> { new Pack("broken", 0, 100), new Pack("ok", 3, 900) }) | "ok" |
CheapestPack(new List<Pack> { }) | null |
Hint
Cross-multiply instead of dividing: a.price * b.units against b.price * a.units keeps it in integers.
Reference solution in C#
public string CheapestPack(List<Pack> packs) {
Pack best = null;
foreach (var p in 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;
}