Drill

ProblemsJava › orders

Pick the coupon worth most

mediumordersArraysGreedyMathJava

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?

Java 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

String bestCoupon(int basketTotal, List<Coupon> coupons) {
    
}

Worked examples

CallResult
bestCoupon(10000, Main.<Coupon>ls(new Coupon("TEN", 10, 5000), new Coupon("BIG", 50, 2000)))"BIG"
bestCoupon(10000, Main.<Coupon>ls(new Coupon("ZED", 20, 9000), new Coupon("ACE", 20, 9000)))"ACE"
bestCoupon(100, Main.<Coupon>ls(new Coupon("TINY", 0, 500)))(String) null
bestCoupon(10000, Main.<Coupon>ls())(String) null

Hint

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

Reference solution in Java
String bestCoupon(int basketTotal, List<Coupon> coupons) {
    String bestCode = null;
    int bestSave = 0;
    for (Coupon c : coupons) {
        int save = Math.min((basketTotal * c.percentOff) / 100, c.maxOff);
        if (save <= 0) continue;
        if (save > bestSave || (save == bestSave && bestCode != null && c.code.compareTo(bestCode) < 0)) {
            bestSave = save;
            bestCode = c.code;
        }
    }
    return bestCode;
}

The same problem in another language

More orders problems in Java