Problems › TypeScript › patterns
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
Where you start
function firstDayUnder(movements: number[]): number {
}
Worked examples
| Call | Result |
|---|---|
firstDayUnder([100,-30,-90]) | 3 |
firstDayUnder([100,50]) | 0 |
firstDayUnder([-1]) | 1 |
firstDayUnder([]) | 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 TypeScript
function firstDayUnder(movements: number[]): number {
let balance = 0;
for (let i = 0; i < movements.length; i += 1) {
balance += movements[i];
if (balance < 0) return i + 1;
}
return 0;
}