Pick the coupon worth most
A customer has several coupons in their wallet and the checkout applies whichever saves them the most on this basket.
- A coupon takes its percentage off, but never more than its cap.
- Choose the coupon with the largest saving.
- If two save the same, take the one whose code sorts first.
- If nothing saves anything, return null.
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.
Where you start
String bestCoupon(int basketTotal, List<Coupon> coupons) {
}
Worked examples
| Call | Result |
|---|---|
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;
}