Drill

ProblemsC++ › patterns

The day the account went under

easypatternsPrefix sumsArraysC++

A cash-flow view replays a month of movements and flags the first day the balance dropped below zero.

firstDayUnder(movements: list<int>) → 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 firstDayUnder(std::vector<int> movements) {
    
}

Worked examples

CallResult
firstDayUnder(std::vector<int>{100, -30, -90})3
firstDayUnder(std::vector<int>{100, 50})0
firstDayUnder(std::vector<int>{-1})1
firstDayUnder(std::vector<int>{})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 C++
int firstDayUnder(std::vector<int> movements) {
    int balance = 0;
    for (size_t i = 0; i < movements.size(); i++) {
        balance += movements[i];
        if (balance < 0) return static_cast<int>(i) + 1;
    }
    return 0;
}

The same problem in another language

More patterns problems in C++