CORR-P5

The best stretch of line

Practice 5 of 5Correctness8 tests

The problem

A line is split into sections. The list a holds the minutes each section gains (a positive number) or loses (a negative number) against the timetable. A stretch is a run of one or more neighbouring sections. Return the largest total of any stretch.

best_stretch([2, -5, 3, 4, -1, 2, -6, 1])
# 8, from the stretch 3, 4, -1, 2
best_stretch([-4, -2, -7])
# -2: a stretch has at least one value

The fast answer uses one pass. To trust it, you need a proof. Lesson 3’s induction gives one: assume you know the best stretch that ends at section i - 1, and show how to get the best stretch that ends at section i.

Limits

  • Up to 200,000 values. The list has at least one value.

Builds on CORR-2 Loop invariants and CORR-3 Proof by induction.

Continue on a laptop

Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.

Need a hint?0 of 3 opened

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

8 tests, not run yet
Test results
#TestResultReads · time
1Mixed gains and lossesNot run
2All positiveNot run
3All negativeNot run
4One valueNot run
5Best at the very endNot run
6A big loss splits two gainsNot run
7ZerosNot run
8200,000 valuesNot run