Module 4 · Smart Patterns for Lists · Lesson 12 of 40

Prefix sums and the best subarray

Precompute running totals to answer range sums instantly, and use Kadane's idea to find the biggest subarray sum.

In this lesson · about 20 minutes

  • Build a prefix-sum list
  • Answer any range sum with one subtraction
  • Find the maximum subarray sum with Kadane's method

Prefix sums

Suppose people keep asking: "What is the sum from index 2 to index 5?" Adding every time is O(n) per question.

Instead, build a prefix list once, where prefix[i] is the total of the first i numbers. Then:

sum of nums[a..b] = prefix[b + 1] − prefix[a]

Building it is O(n) once. After that, every question is O(1).

Try it · see it work

Prefix sums: any range sum in one step

Change the range. The answer always comes from just two prefix boxes.

nums

30
11
42
13
54
95
26
67

prefix (prefix[i] = sum of the first i numbers)

00
31
42
83
94
145
236
257
318

Sum of nums[2..5] = prefix[6] − prefix[2] = 23 − 4 = 19. One subtraction, no matter how long the range is: O(1) per question after an O(n) setup.

Kadane's method: the biggest subarray sum

Question: in [-2, 1, -3, 4, -1, 2, 1, -5, 4], which run of numbers in a row has the biggest total? (Answer: [4, -1, 2, 1], total 6.)

Kadane's idea is simple. Walk the list once, keeping a running total called current. At each number, ask: "Is it better to add this number to my run, or to start a new run here?"

current = best = nums[0]
for x in nums[1:]:
    current = max(x, current + x)
    best = max(best, current)

If the run so far is negative, it only drags you down, so you start fresh. One pass: O(n) time, O(1) space.

Exercise

Build the prefix list

Write build_prefix(nums) that returns a list one longer than nums, starting with 0, where each item is the running total. For [3, 1, 4] return [0, 3, 4, 8].

Exercise

Biggest subarray sum

Write max_subarray(nums) using Kadane's method. The list is not empty.

Check your understanding0 of 2 correct

Question 1

1.prefix = [0, 3, 4, 8, 9]. What is the sum of nums[1..2]?

Question 2

2.In Kadane's method, when do you start a new run?

Quiz score: 0 of 2

Exercises solved: 0 of 2

Tip: answer every quiz question correctly first.

Noviq Academy is free and for learning. This course follows the topics of a set of DSA study notes, rewritten in Noviq's own words with Python examples. Python runs in your own browser with Pyodide; nothing you type is sent to Noviq.