← All lessonsUnit 2 · One pass, remembering something
Lesson 2.3

Running total

One variable holds the total so far, and it is looked at after every step, not only at the end.

Reach for it when
The problem gives changes (gains, steps, deposits) and asks where you are after them.
The move
Add each element to one variable, and look at that variable after every step.
Cost
O(n) time, O(1) extra space.

The idea

Harper

My bank charged me last month for having no money. I finished the month 80 better off than I started.

Arthur

Then you had money.

Harper

At the end. We'll come back to the middle. Here is the month. The account opens empty. Then 50 comes in, 80 goes out, 60 comes in, 90 comes in, 40 goes out. What is in it at the end?

Arthur

80.

Harper

How did you do that?

Arthur

I kept one number in my head. It started at 0, and every line changed it: 50, then -30, then 30, then 120, then 80.

Harper

I asked for one number. You said five.

Arthur

You asked for the last one. There is no way to it except through the other four.

Harper

Were the other four wrong?

Arthur

No. Each was what the account held at that moment. It's the balance. A bank statement prints it beside every line: this is what changed, and this is what you had afterwards.

Harper

That's the picture, then. A statement. Every line is a change, and beside it is the balance after it. Read me the second line.

Arthur

80 went out. Balance: -30. You were overdrawn.

Harper

For one line! I finished on 80!

Arthur

The bank doesn't wait for the last line. It looks at the balance after every one.

Harper

And the loop that adds up an array. When does that look?

Arthur

Once, at the bottom: return total. It carries the balance all the way down the statement in total, and never looks at it on the way.

Harper

How will I know that a problem wants this?

Arthur

It hands you changes and asks where they leave you. Money in and out, and a balance. Climbs and drops, and a height.

Harper

So the whole lesson is: look sooner.

Arthur

Look after every line. The bank already does. It charges for the service.

That is the whole tool: one variable that holds the balance, and a look at it after every line. Everything else in this lesson is that look, with one thing changed at a time.

The shape

This is what you know by heart:

Swift
/// The total after each change, in order.
func runningTotals(_ changes: [Int]) -> [Int] {
    var total = 0                    // the account opens empty
    var totals: [Int] = []
    for change in changes {
        total += change              // one line of the statement
        totals.append(total)         // the balance after it: look at it here
    }
    return totals
}

It has three parts, and each is there for a reason.

The two lines inside the loop come in the order a statement prints them: first the change, then the balance after it. Step, then look.

Watch it run

The statement is 50, -80, 60, 90 and -40: money coming in is above zero, and money going out is below. Here is what each variable holds on each pass.

linechangetotal beforetotal aftertotals after
150050[50]
2-8050-30[50, -30]
360-3030[50, -30, 30]
49030120[50, -30, 30, 120]
5-4012080[50, -30, 30, 120, 80]

The answer is [50, -30, 30, 120, 80]: the statement's balance column. Look at the second row. After that line total is -30, and the account is overdrawn. Nothing in the last row shows it: the month ends on 80. A question about the second row has to be asked on the second pass.

Step by step

Step 1

The sum of an array

Swift
/// What the changes add up to: the total after all of them. No changes add up to 0.
func sum(_ changes: [Int]) -> Int {
    var total = 0
    for change in changes {
        total += change
    }
    return total                     // one look, after the last line
}

This is the loop from "Loops and indexes", with the numbers read as changes. It is the shape with the look taken out of the loop: total is looked at once, after the last line. For the statement it gives 80, the balance the month ends on.

What is new is not in the code. It is the sentence that stays true as the loop runs: after each pass, total is the sum of the changes met so far. On a statement, that is the balance after that line. It is true before the loop, when no line has been met and the account holds 0. Each pass keeps it true. So after the last pass total is the sum of them all.

That sentence is what the rest of the lesson stands on. total is not a half-built sum that only means something at the end. After every pass it is a real balance, and you may look at it.

With no changes at all the loop does not run, and the answer is the 0 the account opened with.

Swift will add up an array in one line: changes.reduce(0, +). It hands back the last total and none of the ones before it. The steps below need the ones before it, so write the loop.

Step 2

The total after each step, as a new array

This is LeetCode 1480, Running Sum of 1d Array. It wants a new array as long as nums: at each position, the sum of nums from the first number up to and including that one. On a statement, that is the balance column.

Swift
/// LeetCode 1480. The sum of `nums` up to and including each position.
func runningSum(_ nums: [Int]) -> [Int] {
    var total = 0
    var totals: [Int] = []
    for number in nums {
        total += number
        totals.append(total)         // the look, inside the loop
    }
    return totals
}

What is new: the look moves inside the loop. totals.append(total) comes straight after the add, so what it writes down is the balance after that line. This is the shape itself, under the names LeetCode gives it.

For the statement it gives [50, -30, 30, 120, 80]. Its last number is step 1's answer, because the last balance is the sum of every line. And it is the "total after" column of the trace above: this function hands back its own trace.

The array is there because this problem asks for every balance. Each step below asks one question about the balances, and answers it as they go by, without keeping them.

Step 3

The largest total reached along the way

What was the highest balance of the month? You could make the column with step 2, and then find its largest number with "Best so far". That is two passes and an array. Do both in one pass: carry the balance, and keep the best one seen so far.

Swift
/// The largest total reached after any of the changes. `changes` is never empty.
func largestTotal(_ changes: [Int]) -> Int {
    var total = 0
    var best = changes[0]            // the first balance: an empty account and one line
    for change in changes {
        total += change
        if total > best {            // the look is a challenge
            best = total             // the balance is kept, not the change
        }
    }
    return best
}

What is new: the look is a challenge. After each line the balance walks up to the chair from "Best so far", and takes it if it is larger. It is the balance that is compared and kept, not the change.

For the statement the answer is 120, the balance after line 4. It is not the largest change, which is 90, and it is not the last balance, which is 80. Only a look after every line finds it.

best starts from something real, as it did in "Best so far": the first balance in the column. An empty account and one line make a balance equal to that line, so the first balance is changes[0]. The loop then meets that first balance again and compares it with itself, which does no harm. The problem promises at least one change, so there is a first balance to start from.

The 0 the account opened with is not in the column, because no line produced it. Take a month in which money only goes out: -20, -30 and -10. The balances are -20, -50 and -60, and the highest of them is -20. Start best at 0 and the function answers 0, a balance the column never showed. This step's second problem hands you that version to mend.

Whether the start counts is for the problem to say. This one says it does not. LeetCode 1732, at the end of this lesson, says it does.

Step 4

Does the total ever go below zero?

Swift
/// Whether the total is below zero after any of the changes.
func goesBelowZero(_ changes: [Int]) -> Bool {
    var total = 0
    for change in changes {
        total += change
        if total < 0 {               // the look is a test
            return true              // overdrawn: nothing later can undo that
        }
    }
    return false                     // every balance was looked at
}

What is new: the look is a test, and it can end the walk. The moment a balance is below zero, the answer is yes. Nothing that comes in afterwards can change that: the account was overdrawn, however the month ends. So the function returns there and then, the way "Count as you go" returns the moment its answer is settled.

For the statement the answer is true, settled at line 2. The 3 lines after it are never read.

return false has to wait until the loop is over. A yes needs one balance below zero. A no needs every balance looked at.

A balance of exactly 0 is not below zero, so the test is < and not <=. For 50 and -50 the balance comes down to 0, and the answer is false.

The add comes before the look, as it does in the shape. Swap the two and each look sees the balance before its line, so the balance after the last line is never looked at. For 50 and -80 that version answers false, and the account ends the month overdrawn. This step's second problem is that version, to mend.

Step 5

The step at which the total first passes 100

Swift
/// The position of the first change that leaves the total above 100, or `nil` when the
/// total is never above 100.
func firstPast100(_ changes: [Int]) -> Int? {
    var total = 0
    for i in changes.indices {
        total += changes[i]
        if total > 100 {
            return i                 // the line that did it
        }
    }
    return nil                       // no line did
}

What is new: the answer is where. The look hands back the position of the line that did it, so the loop walks changes.indices, as it did in "Best so far" when the chair held a position.

For the statement the answer is 3: the line at position 3 takes the balance from 30 to 120. Positions start at 0, so that is line 4 of the trace.

The words of the problem settle three things.

  • Passes means more than 100, so the test is >. A balance of exactly 100 has reached 100 and not passed it. For 60, 40 and 5 the balances are 60, 100 and 105, and the answer is 2.
  • First means the function returns at once. The balance may drop back and pass 100 again later, and that changes nothing.
  • It may never happen. For 30 and 30 the balance ends on 60, and there is no position to give. So the function returns Int?, and nil says that no line did it, as "Count as you go" did for a position that may not be there. Returning 0 would not do: 0 is a position, the first line.
Step 6

The same, starting from a given amount instead of zero

Swift
/// The same, for a total that starts at `start`, which is 100 or less.
func firstPast100(_ changes: [Int], from start: Int) -> Int? {
    var total = start                // the only new line: the opening balance
    for i in changes.indices {
        total += changes[i]
        if total > 100 {
            return i
        }
    }
    return nil
}

What is new: one line. The account does not open empty. It opens with start, so total begins there.

The 0 in every step so far was never part of the tool. It was the opening balance of an account that opened empty. total starts as whatever you have before the first change.

Take the same statement with 60 in the account when the month begins. The first line takes the balance to 110, so the answer is 0. From 0 it was 3.

The problem promises a start of 100 or less. A start above 100 would be past 100 before any line, and no position says that. When a problem does not promise it, decide what that means before the loop.

Find the Highest Altitude

A cyclist sets off from altitude 0. gain holds one number for each climb of the ride: how much the altitude changes over that stretch of road. A climb above zero goes up, and a climb below zero goes down. The question is the highest altitude of any point on the ride.

The words are this tool's signal. The problem hands you changes, and asks about where they leave you. A gain is a line of the statement, and the altitude is the balance.

It comes in two small steps, and you have most of each already.

First, the altitude after each climb.

Swift
/// The altitude after each climb of a ride that starts at altitude 0.
func altitudeAfterEachClimb(_ gain: [Int]) -> [Int] {
    var altitude = 0                 // the ride starts at altitude 0
    var altitudes: [Int] = []
    for change in gain {
        altitude += change
        altitudes.append(altitude)
    }
    return altitudes
}

For gains of -3, 5, 2, -6 and 4 this gives [-3, 2, 4, -2, 2]. Nothing in the code is new: it is the shape, with gain for changes and altitude for total. What is new is seeing that in the problem's words.

Notice one thing. There is one altitude here for each gain, and the ride has one more point than that: the start. It was at altitude 0, no gain produced it, and it is not in this array.

Next, the highest of them, counting the start.

Swift
/// The highest point of a ride that starts at altitude 0. `altitudes` holds the altitude
/// after each climb, and the start counts as a point too.
func highestPoint(_ altitudes: [Int]) -> Int {
    var highest = 0                  // the start: a point of the ride, at altitude 0
    for altitude in altitudes {
        if altitude > highest {
            highest = altitude
        }
    }
    return highest
}

What is new: the start counts, so the start goes in the chair first. That makes the first line var highest = 0, which is the line "Best so far" told you not to write.

It is right here, and for that lesson's own reason. The rule was never "not zero". It was "start from something real": the first thing met. In an array of numbers the first thing met is numbers[0], and a zero in the chair was a number that nobody had entered. On this ride the first thing met is the start, and its altitude is 0. The cyclist really stood there, and the problem counts it as a point. So 0 is the first altitude of the ride, and it is the highest so far before any climb.

For the ride above the answer is 4. Now take a ride that only goes down: -4, -1 and -6. The altitudes are -4, -5 and -11, and the answer is 0: the highest point was the start. Begin from altitudes[0] out of habit and the answer comes out as -4, which leaves out a point the problem counts. This step's second problem hands you that version to mend.

Then the problem itself. Carry the altitude and keep the highest in one pass, with no array, as step 3 did.

Swift
/// LeetCode 1732. The highest altitude of a ride that starts at altitude 0.
func largestAltitude(_ gain: [Int]) -> Int {
    var altitude = 0                 // the start
    var highest = 0                  // the start is the highest point so far
    for change in gain {
        altitude += change
        if altitude > highest {
            highest = altitude
        }
    }
    return highest
}

It gives 4 for the first ride and 0 for the one that only goes down. Set it beside step 3. One line is different: where the best starts. There the start did not count, so best began as the first balance. Here the start counts, so highest begins as the start.

Both variables begin at 0 for one reason: both begin where the ride begins. If the ride began at some other altitude, both would begin there, as total did in step 6.

What goes wrong

Looking only at the end. The statement adds up to 80, which is above zero. Ask only whether the sum is below zero and the answer is false: never overdrawn. The balance was -30 after the second line. A question about the way there needs a look on the way.

Looking before adding. With the look above total += change, every look sees the balance before its line. The shape then gives [0, 50, -30, 30, 120] for the statement: it begins with the opening 0, and the last balance, 80, never appears. Step 4 written that way answers false for 50 and -80, where the answer is true.

Looking at the change, not the total. if change < 0 asks whether money ever went out, which is a different question. For 50 and -20 it says true. The balances were 50 and 30, never below zero, and the answer is false. The look is at total.

The wrong start for the best, either way. When the start does not count, var best = 0 puts a balance in the chair that the column never showed: for -20, -30 and -10 it answers 0, where the answer is -20. When the start does count, beginning from the first altitude leaves the start out: for a ride of -4, -1 and -6 it answers -4, where the answer is 0. Before you write that line, ask the problem one thing: is the start one of the things being compared?

Reaching is not passing. With >=, step 5 returns the line that reaches 100. For 60, 40 and 5 it answers 1, where the answer is 2.

The wrong kind of answer. Step 5 asks where, so the answer for the statement is the position, 3, and not the balance, 120. And when no line does it, the answer is not a position at all: for 30 and 30 it is nil. A 0 there would say that the first line did it.

Forgetting the start. var total = 0 is wrong when the problem hands you a start. For the statement with 60 in the account to begin with, it answers 3, where the answer is 0.

Say it back

1

What does total hold after each pass of the loop?

Show the answerHide the answer

The sum of the changes met so far. On a statement, that is the balance after that line.

2

Where does the look go, and why there?

Show the answerHide the answer

Inside the loop, straight after total += change. There total is the balance after this line. Before the add it is the balance before the line, and the balance after the last line would never be looked at.

3

"Does the total ever go below zero?" When can you answer yes, and when no?

Show the answerHide the answer

Yes, the moment one balance is below zero: nothing later can undo it, so return there. No, only after the loop, when every balance has been looked at.

4

The total first passes 100. What do you return, and what if it never does?

Show the answerHide the answer

The position of the change that did it, so the loop walks changes.indices. Passes means >. If it never happens, return nil.

5

What does total start as?

Show the answerHide the answer

Whatever there is before the first change. That is 0 when the problem says nothing, and start when it hands you one.

6

var best = 0 was wrong in "Best so far". Why is var highest = 0 right in LeetCode 1732?

Show the answerHide the answer

There, zero was not one of the numbers. Here the ride begins at altitude 0 and the start counts as a point, so 0 is the first real altitude. The rule is the same in both: start from something real.

7

How was Harper charged for having no money in a month she finished 80 better off?

Show the answerHide the answer

The bank looked at the balance after every line, and after the second it was -30. Adding up the month looks once, at the end, and sees 80. A running total is that same variable, looked at after every step.

Practise

These are this lesson's problems in the Orithms app, in the order they come.

ProblemLevel
1What the changes add up toEasy
2The total after each stepEasy
3The largest total along the wayEasy
4A total that was never reachedEasy
5Does the total ever go below zero?Easy
6The last total is never looked atEasy
7The step that first passes 100Easy
8Starting from a given amountEasy
9The altitude after each climbEasy
10The highest point, counting the startEasy
11The start is a point tooEasy
12Find the highest altitudeEasy

These problems are done in the Orithms Mac app.

Every piece of code and every number in a lesson comes from a file that was compiled and run.