Drill

ProblemsC# › pricing

Which pack size is the best value

mediumpricingArraysMathC#

The same product sits on the shelf in several pack sizes. A price-comparison badge needs the one with the lowest cost per unit.

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.

Solve it in Python →

Where you start

public string CheapestPack(List<Pack> packs) {
    
}

Worked examples

CallResult
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;
}

The same problem in another language

More pricing problems in C#