Bank app~18 min2s · 256 MBtarget O(n) time, O(1) spacekadane
A savings app reports how far the value of an account fell from its best earlier value. A fall of 500 units matters little when the account was worth 2,000. It matters a lot when the account was worth 100. So the app measures every fall as a share of the earlier high.
You are given the value of the account at the end of each day. You must find the day on which the fall, measured as a share of the highest value so far, was the largest.
Write steepest_percent_fall(values).
values[d] is the value on day d. It is always at least 1.d, the peak is the highest value on days 0 to d, and the fall is (peak - values[d]) / peak.[peak, values[d]] for that day. If no day has a fall above 0, return [0, 0].Input: values = [100, 50, 2000, 1500, 1800]
Output: [100, 50]A fall is the drop from the peak as a fraction of the peak. The last column keeps the steepest fall so far.
| Day | Value | Peak so far | Fall from the peak | Steepest fall so far |
|---|---|---|---|---|
| 0 | 100 | 100 | 0 / 100 | 0 / 1 |
| 1 | 50 | 100 | 50 / 100 | 50 / 100 |
| 2 | 2000 | 2000 | 0 / 2000 | 50 / 100 |
| 3 | 1500 | 2000 | 500 / 2000 | 50 / 100 |
| 4 | 1800 | 2000 | 200 / 2000 | 50 / 100 |
On day 1 the value 50 is 50 percent below the peak 100. On day 3 the value 1500 is only 25 percent below the peak 2000, although the fall is larger in units. The table shows each day.
Input: values = [5, 6, 7]
Output: [0, 0]The series never falls, so the answer is [0, 0].
Input: values = [10, 5, 20, 10]
Output: [10, 5]Day 1 falls from 10 to 5 and day 3 falls from 20 to 10. Both are 50 percent, so the earliest day wins.
1 ≤ values.length ≤ 100,000 (days)1 ≤ values[d] ≤ 1,000,000 (units)The products in the comparison reach about 10^12, so they need 64-bit numbers.
Measuring the fall for every pair of days costs about n × n / 2 steps, 5 × 10^9 at n = 100,000. For a fixed day, the largest fall is always measured from the highest earlier value, so a running peak is enough, and one pass finds the answer.