Overview
Find the longest strictly rising sequence of prices, skipping any in between, in O(n log n) with a list of best tails and binary search.
- a subsequence may skip items
- tails[k]: smallest end of a rise of length k + 1
- bisect_left finds the tail to replace
Short Course
For the longest rising subsequence, keep tails[k]: the smallest last value
of a rise of length k + 1. Each new price replaces the first tail >= it,
found by binary search, or extends the list. Trap: a subsequence may skip
items; a subarray can't.
from bisect import bisect_left
tails = [2, 5, 9]
bisect_left(tails, 6) # 2: 6 would replace 9
bisect_left(tails, 10) # 3: 10 extends the list
Task
Write longest_rise(prices): the length of the longest strictly increasing
subsequence of prices. Example: longest_rise([3, 1, 4, 1, 5, 9, 2, 6])
→ 4 (for instance 1, 4, 5, 9).
Test Suites
Pending
Next
Output