Skip to content
CodeItRaw
Arrays

Lesson 6/6

If at every element you need something like "the sum of the numbers to its left" or "the lowest price so far", do not work it out from the start each time. Update it as you go: add the new element to the value from before.

total = sum(values)
left = 0
for i, v in enumerate(values):
if left == total - left - v:
return i
left += v
return -1
enumerate gives the position and the value together. The sum on the right needs no variable of its own: take the left and the element itself from the total and the right is what remains. left grows after the comparison.

The best buy-and-sell is the same idea: carry "the lowest price up to today" and the profit of selling today is one subtraction. One pass in place of two nested loops.

Tasks

Tasks open in order. Solve them all and the next lesson opens.

This lesson's tasks open when the lessons before it are finished. You can read the explanation now.Go to the current lesson

  1. 01

    Balance Point

    Function

  2. 02

    Halving

    Code reading · Read the Big-O

  3. 03

    Price Watch

    Function

If you would rather not wait for the order, every problem is open without locks: Problem list