Problems › JavaScript › orders
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?
Where you start
function bestCoupon(basketTotal, coupons) {
}
Worked examples
| Call | Result |
|---|---|
bestCoupon(10000, [{"code":"TEN","percentOff":10,"maxOff":5000},{"code":"BIG","percentOff":50,"maxOff":2000}]) | "BIG" |
bestCoupon(10000, [{"code":"ZED","percentOff":20,"maxOff":9000},{"code":"ACE","percentOff":20,"maxOff":9000}]) | "ACE" |
bestCoupon(100, [{"code":"TINY","percentOff":0,"maxOff":500}]) | null |
bestCoupon(10000, []) | null |
Hint
Work out each saving first, then compare. Integer division truncates, which is in the shop’s favour.
Reference solution in JavaScript
function bestCoupon(basketTotal, coupons) {
let bestCode = null, bestSave = 0;
for (const c of coupons) {
const save = Math.min(Math.floor((basketTotal * c.percentOff) / 100), c.maxOff);
if (save <= 0) continue;
if (save > bestSave || (save === bestSave && bestCode !== null && c.code < bestCode)) {
bestSave = save;
bestCode = c.code;
}
}
return bestCode;
}