The day the account went under
A cash-flow view replays a month of movements and flags the first day the balance dropped below zero.
- The balance starts at zero and each movement is applied in order.
- Days are numbered from 1.
- Return the first day the running balance is below zero.
- If it never goes under, return 0.
firstDayUnder(movements: list<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 firstDayUnder(List<Integer> movements) {
}
Worked examples
| Call | Result |
|---|---|
firstDayUnder(Main.<Integer>ls(100, -30, -90)) | 3 |
firstDayUnder(Main.<Integer>ls(100, 50)) | 0 |
firstDayUnder(Main.<Integer>ls(-1)) | 1 |
firstDayUnder(Main.<Integer>ls()) | 0 |
Hint
This is a running total with one test each step. There is nothing to look back at — you only need the balance so far.
Reference solution in Java
int firstDayUnder(List<Integer> movements) {
int balance = 0;
for (int i = 0; i < movements.size(); i++) {
balance += movements.get(i);
if (balance < 0) return i + 1;
}
return 0;
}