Monitoring~30 min2s · 256 MBtarget O(n²) time, O(n) spaceclassic twin: lc-673dp
A monitoring system records one reading from a sensor every minute. An engineer looks for rising trends: a run of readings picked in time order, each strictly higher than the one before. The readings in a run need not be neighbours.
The longest rising trends are the most useful. Your team lead asks: "How many different runs have the longest length?"
Write count_longest_rising(readings).
readings lists the readings in time order.1,000,000,007.Input: readings = [1, 3, 5, 4, 7]
Output: 2For each reading i, let length[i] be the longest run that ends at i, and count[i] the number of runs with that length. Look at every earlier reading j that is lower. A longer run replaces the old best and takes its count. A run of equal length adds its count.
| i | Reading | Earlier lower readings | length[i] | count[i] |
|---|---|---|---|---|
| 0 | 1 | none | 1 | 1 |
| 1 | 3 | 1: longer, length 2, count 1 | 2 | 1 |
| 2 | 5 | 1: longer, length 2, count 1; 3: longer, length 3, count 1 | 3 | 1 |
| 3 | 4 | 1: longer, length 2, count 1; 3: longer, length 3, count 1 | 3 | 1 |
| 4 | 7 | 1: longer, length 2, count 1; 3: longer, length 3, count 1; 5: longer, length 4, count 1; 4: same length, count 2 | 4 | 2 |
The longest length is 4. The runs that end at readings with length 4 number 2: 1, 3, 5, 7 and 1, 3, 4, 7.
Input: readings = [4, 4, 4]
Output: 3No reading is higher than another. The longest run has length 1, and each of the three positions is its own run.
Input: readings = [1, 2, 3]
Output: 1The readings rise all the way, so there is one longest run.
1 ≤ len(readings) ≤ 1,5000 ≤ readings[i] ≤ 1,000,000There can be 1,500 readings, and each can be in a run or not, so there are 2 to the power 1,500 choices. A table with one entry for each reading, and a look at every earlier reading for each entry, takes about 1.1 million steps.