Drill

ProblemsC# › orders

Pick the coupon worth most

mediumordersArraysGreedyMathC#

A customer has several coupons in their wallet and the checkout applies whichever saves them the most on this basket.

BestCoupon(basketTotal: int, coupons: list<Coupon>) → 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 BestCoupon(int basketTotal, List<Coupon> coupons) {
    
}

Worked examples

CallResult
BestCoupon(10000, new List<Coupon> { new Coupon("TEN", 10, 5000), new Coupon("BIG", 50, 2000) })"BIG"
BestCoupon(10000, new List<Coupon> { new Coupon("ZED", 20, 9000), new Coupon("ACE", 20, 9000) })"ACE"
BestCoupon(100, new List<Coupon> { new Coupon("TINY", 0, 500) })null
BestCoupon(10000, new List<Coupon> { })null

Hint

Work out each saving first, then compare. Integer division truncates, which is in the shop’s favour.

Reference solution in C#
public string BestCoupon(int basketTotal, List<Coupon> coupons) {
    string bestCode = null;
    int bestSave = 0;
    foreach (var c in coupons) {
        int save = Math.Min((basketTotal * c.PercentOff) / 100, c.MaxOff);
        if (save <= 0) continue;
        if (save > bestSave || (save == bestSave && bestCode != null && string.CompareOrdinal(c.Code, bestCode) < 0)) {
            bestSave = save;
            bestCode = c.Code;
        }
    }
    return bestCode;
}

The same problem in another language

More orders problems in C#