Drill

ProblemsC++ › billing

Apply credits to an invoice

mediumbillingArraysGreedyC++

Customer credits are applied against an invoice in order. Return the remaining unpaid balance.

creditFirst(invoiceTotal: int, credits: list<Credit>) → 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.

Solve it in Python →

Where you start

int creditFirst(int invoiceTotal, std::vector<Credit> credits) {
    
}

Worked examples

CallResult
creditFirst(10000, std::vector<Credit>{Credit{3000}, Credit{5000}})2000
creditFirst(5000, std::vector<Credit>{Credit{3000}})2000
creditFirst(2000, std::vector<Credit>{Credit{5000}})0
creditFirst(0, std::vector<Credit>{Credit{1000}})0

Hint

Walk the credits, subtract each, and clamp at each step.

Reference solution in C++
int creditFirst(int invoiceTotal, std::vector<Credit> credits) {
    int balance = invoiceTotal;
    for (const auto& c : credits) { balance -= c.amount; if (balance < 0) balance = 0; }
    return balance;
}

The same problem in another language

More billing problems in C++