Price an order across volume tiers
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.
- Tiers arrive sorted by upTo, which is a running total, not a slice width.
- A tier covers the units between where the previous tier stopped and its own upTo.
- Anything beyond the last tier is charged at the last tier rate.
- A quantity of zero or less costs nothing.
TieredTotal(qty: int, tiers: list<Tier>) → int
C# 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
public int TieredTotal(int qty, List<Tier> tiers) {
}
Worked examples
| Call | Result |
|---|---|
TieredTotal(60, new List<Tier> { new Tier(10, 100), new Tier(50, 90), new Tier(200, 80) }) | 5400 |
TieredTotal(5, new List<Tier> { new Tier(10, 100), new Tier(50, 90) }) | 500 |
TieredTotal(300, new List<Tier> { new Tier(10, 100), new Tier(50, 90) }) | 27100 |
TieredTotal(0, new List<Tier> { new Tier(10, 100) }) | 0 |
Hint
Track how many units you have already priced. Each tier handles at most upTo minus that.
Reference solution in C#
public int TieredTotal(int qty, List<Tier> tiers) {
if (qty <= 0 || tiers.Count == 0) return 0;
int done = 0, total = 0;
foreach (var t in tiers) {
int 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.Count - 1].UnitPrice;
return total;
}