Online store~35 min2s · 256 MBtarget O(n log n) time, O(n) spaceclassic twin: lc-300dp
A shop's app ships a nightly build. Each build has a version number and adds some test coverage, measured in points. Builds are not always shipped in version order, because teams merge in different orders.
The release manager wants to certify a run of builds. The run keeps the nights in order, and every build in it must have a strictly higher version than the one before. The builds in between are skipped. She wants the run with the most coverage points in total.
Write best_rising_total(versions, coverage).
versions[i] is the version number of the build on night i, and coverage[i] is the points it adds. Both lists have the same length.i1 < i2 < ... < ik with versions[i1] < versions[i2] < ... < versions[ik]. Equal versions do not rise.Input: versions = [3, 1, 4, 2, 5], coverage = [4, 6, 3, 5, 2]
Output: 13The solution finds, for each build, the best total of a run that ends with it. That is its coverage plus the best total of a run that ends at an earlier build with a lower version.
| Build | Version | Coverage | Best run ending here | Chosen from |
|---|---|---|---|---|
| 0 | 3 | 4 | 4 | nothing before |
| 1 | 1 | 6 | 6 | nothing before |
| 2 | 4 | 3 | 9 | build 1 |
| 3 | 2 | 5 | 11 | build 1 |
| 4 | 5 | 2 | 13 | build 3 |
The best run is builds 1, 3 and 4, with versions 1, 2 and 5 and coverage 6, 5 and 2. Its total is 13.
Input: versions = [5, 1, 2, 3], coverage = [100, 1, 1, 1]
Output: 100The longest rising run has 3 builds but only 3 points. The single build with version 5 has 100 points.
Input: versions = [2, 2, 2], coverage = [5, 5, 5]
Output: 5Equal versions do not rise, so a run has one build, and the answer is 5.
1 ≤ len(versions) = len(coverage) ≤ 100,0001 ≤ versions[i] ≤ 1,000,000, and 1 ≤ coverage[i] ≤ 10,000Comparing every build with every earlier build takes about 5,000,000,000 comparisons. A tree that answers a prefix maximum in about 17 steps brings that to about 3,400,000 steps. The best total can reach 1,000,000,000, which is large enough that 64-bit totals are the safe choice.