Apply credits to an invoice
Customer credits are applied against an invoice in order. Return the remaining unpaid balance.
- Apply credits in list order, each subtracting from the running balance.
- The balance is clamped at 0 — credits never produce a negative result.
creditFirst(invoiceTotal: int, credits: list<Credit>) → int
Go 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
func creditFirst(invoiceTotal int, credits []Credit) int {
}
Worked examples
| Call | Result |
|---|---|
creditFirst(10000, []Credit{Credit{Amount: 3000}, Credit{Amount: 5000}}) | 2000 |
creditFirst(5000, []Credit{Credit{Amount: 3000}}) | 2000 |
creditFirst(2000, []Credit{Credit{Amount: 5000}}) | 0 |
creditFirst(0, []Credit{Credit{Amount: 1000}}) | 0 |
Hint
Walk the credits, subtract each, and clamp at each step.
Reference solution in Go
func creditFirst(invoiceTotal int, credits []Credit) int {
balance := invoiceTotal
for _, c := range credits {
balance -= c.Amount
if balance < 0 {
balance = 0
}
}
return balance
}