Compute the final charge on an order
Combine a subtotal, an optional discount, and shipping to produce the final amount due.
- Subtract the discount from the subtotal, clamped at zero.
- Then add the shipping cost.
finalCharge(subtotal: int, discount: int, shipping: int) → int
Java 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
int finalCharge(int subtotal, int discount, int shipping) {
}
Worked examples
| Call | Result |
|---|---|
finalCharge(5000, 500, 800) | 5300 |
finalCharge(1000, 2000, 500) | 500 |
finalCharge(3000, 0, 1000) | 4000 |
finalCharge(0, 0, 0) | 0 |
Hint
Max(0, subtotal − discount) then add shipping.
Reference solution in Java
int finalCharge(int subtotal, int discount, int shipping) {
int net = subtotal > discount ? subtotal - discount : 0;
return net + shipping;
}