Drill

ProblemsJavaScript › orders

Pick the coupon worth most

mediumordersJavaScript

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?

Solve it in the editor →

Where you start

function bestCoupon(basketTotal, coupons) {
  
}

Worked examples

CallResult
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;
}

The same problem in another language

More orders problems in JavaScript