ADDP-P6

The cheapest trip

Practice 6 of 6Advanced DP11 tests

The problem

Stations lie along a line at positions x[0] < x[1] < …. A train starts at the first station and ends at the last. It may stop at any stations in between. Each run from one stop to the next stop, i to j, costs (x[j] − x[i]) ** 2 + c. Find the cheapest total.

cheapest_trip([0, 1, 2], 1)        # 4: stop at 1
cheapest_trip([1, 2, 3, 4, 5], 6)  # 20: stop at 3

Limits

  • Up to 150,000 stations; positions up to about 10⁹ (a thousand million); c up to 10¹² (a million million).
  • Trying every earlier stop for every station is about 10¹⁰ steps (ten thousand million). Aim for O(n).
  • Answers can be near 10¹⁸. Keep to whole numbers.

Builds on ADDP-6 DP optimisations.

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.

11 tests, not run yet
Test results
#TestResultReads · time
1One stationNot run
2Two stationsNot run
3Stopping helpsNot run
4Stopping costs too muchNot run
5Free stopsNot run
6Five stationsNot run
7Far apartNot run
8Eight stationsNot run
9150,000 stationsNot run
10Even spacingNot run
11Long runs between stopsNot run