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

std::optional<std::string> cheapestPack(std::vector<Pack> packs) {
    
}

Worked examples

CallResult
cheapestPack(std::vector<Pack>{Pack{std::string("single"), 1, 300}, Pack{std::string("six"), 6, 1500}, Pack{std::string("crate"), 24, 6200}})std::optional<std::string>(std::string("six"))
cheapestPack(std::vector<Pack>{Pack{std::string("a"), 2, 200}, Pack{std::string("b"), 4, 400}})std::optional<std::string>(std::string("b"))
cheapestPack(std::vector<Pack>{Pack{std::string("broken"), 0, 100}, Pack{std::string("ok"), 3, 900}})std::optional<std::string>(std::string("ok"))
cheapestPack(std::vector<Pack>{})std::nullopt

Hint

Cross-multiply instead of dividing: a.price * b.units against b.price * a.units keeps it in integers.

Reference solution in C++
std::optional<std::string> cheapestPack(std::vector<Pack> packs) {
    const Pack* best = nullptr;
    for (const auto& p : packs) {
        if (p.units <= 0) continue;
        if (!best) { best = &p; continue; }
        long long a = (long long) p.price * best->units, b = (long long) best->price * p.units;
        if (a < b || (a == b && p.units > best->units)) best = &p;
    }
    if (!best) return std::nullopt;
    return best->label;
}

The same problem in another language

More pricing problems in C++