Split a bill without losing a kuruş
A table of friends splits the bill. The app has to hand out whole minor units that add back to exactly what was charged.
- Everyone pays the same, except that the remainder is handed out one unit at a time, starting from the first person.
- The shares must add back to the total exactly.
- Nobody at the table, or a negative total, gives an empty list.
SplitBill(total: int, people: int) → list<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 List<int> SplitBill(int total, int people) {
}
Worked examples
| Call | Result |
|---|---|
SplitBill(1000, 3) | new List<int> { 334, 333, 333 } |
SplitBill(1000, 4) | new List<int> { 250, 250, 250, 250 } |
SplitBill(10, 4) | new List<int> { 3, 3, 2, 2 } |
SplitBill(0, 3) | new List<int> { 0, 0, 0 } |
Hint
Base share is total / people. The first (total % people) people pay one more.
Reference solution in C#
public List<int> SplitBill(int total, int people) {
if (people <= 0 || total < 0) return new List<int>();
int bas = total / people, extra = total % people;
var shares = new List<int>();
for (int i = 0; i < people; i++) shares.Add(i < extra ? bas + 1 : bas);
return shares;
}