Drill

ProblemsJavaScript › pricing

Price an order across volume tiers

mediumpricingJavaScript

A wholesaler charges less per unit the more you buy, and the tiers stack: the first slice of the order is charged at the first rate, the next slice at the second, and so on.

tieredTotal(qty: int, tiers: list<Tier>) → int

Solve it in the editor →

Where you start

function tieredTotal(qty, tiers) {
  
}

Worked examples

CallResult
tieredTotal(60, [{"upTo":10,"unitPrice":100},{"upTo":50,"unitPrice":90},{"upTo":200,"unitPrice":80}])5400
tieredTotal(5, [{"upTo":10,"unitPrice":100},{"upTo":50,"unitPrice":90}])500
tieredTotal(300, [{"upTo":10,"unitPrice":100},{"upTo":50,"unitPrice":90}])27100
tieredTotal(0, [{"upTo":10,"unitPrice":100}])0

Hint

Track how many units you have already priced. Each tier handles at most upTo minus that.

Reference solution in JavaScript
function tieredTotal(qty, tiers) {
  if (qty <= 0 || tiers.length === 0) return 0;
  let done = 0, total = 0;
  for (const t of tiers) {
    const take = Math.min(qty - done, t.upTo - done);
    if (take > 0) { total += take * t.unitPrice; done += take; }
  }
  if (done < qty) total += (qty - done) * tiers[tiers.length - 1].unitPrice;
  return total;
}

The same problem in another language

More pricing problems in JavaScript