Drill

ProblemsGo › pricing

Which pack size is the best value

mediumpricingArraysMathGo

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?

Go 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

func cheapestPack(packs []Pack) *string {
	
}

Worked examples

CallResult
cheapestPack([]Pack{Pack{Label: "single", Units: 1, Price: 300}, Pack{Label: "six", Units: 6, Price: 1500}, Pack{Label: "crate", Units: 24, Price: 6200}})pStr("six")
cheapestPack([]Pack{Pack{Label: "a", Units: 2, Price: 200}, Pack{Label: "b", Units: 4, Price: 400}})pStr("b")
cheapestPack([]Pack{Pack{Label: "broken", Units: 0, Price: 100}, Pack{Label: "ok", Units: 3, Price: 900}})pStr("ok")
cheapestPack([]Pack{})nil

Hint

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

Reference solution in Go
func cheapestPack(packs []Pack) *string {
	var best *Pack
	for i := range packs {
		p := &packs[i]
		if p.Units <= 0 {
			continue
		}
		if best == nil {
			best = p
			continue
		}
		a, b := p.Price*best.Units, best.Price*p.Units
		if a < b || (a == b && p.Units > best.Units) {
			best = p
		}
	}
	if best == nil {
		return nil
	}
	return &best.Label
}

The same problem in another language

More pricing problems in Go