Bank app~15 min2s · 256 MBtarget O(n) time, O(n) spacesliding-window-fixed
A savings app charts the price of a fund unit with two moving averages. The fast one covers the last few days, and the slow one covers many more. Traders watch the days when the fast average is above the slow one.
You are asked to count those days over a history. Prices are whole units, and the comparison must be exact: two averages that are equal do not count, and no rounding is allowed.
Write count_fast_above_slow(prices, fast, slow).
prices[d] is the price on day d, and 1 <= fast < slow <= prices.length.d is tested when d >= slow - 1, so that both windows are full. The fast average is the mean of the last fast prices up to and including day d. The slow average is the mean of the last slow prices up to and including day d.Input: prices = [10, 12, 11, 15, 9, 7], fast = 2, slow = 4
Output: 2The table gives the sums of both windows on each tested day.
| Day | Fast sum (2 prices) | Slow sum (4 prices) | Fast sum × 4 | Slow sum × 2 | Fast above slow? |
|---|---|---|---|---|---|
| 3 | 26 | 48 | 104 | 96 | yes |
| 4 | 24 | 47 | 96 | 94 | yes |
| 5 | 16 | 42 | 64 | 84 | no |
The tested days are 3, 4 and 5. The table compares the two averages by multiplying out: fast sum / 2 > slow sum / 4 means fast sum × 4 > slow sum × 2. Days 3 and 4 count.
Input: prices = [5, 5, 5], fast = 1, slow = 3
Output: 0Only day 2 is tested, and both averages are 5. Equal averages do not count.
Input: prices = [1, 2, 3, 4], fast = 1, slow = 2
Output: 3The fast window is one price and the slow window is two. On days 1, 2 and 3 the latest price is above the average of the last two.
2 ≤ prices.length ≤ 100,000 (days)1 ≤ prices[d] ≤ 100,000 (units)1 ≤ fast < slow ≤ prices.lengthThe sums reach about 10^10, and the products in the comparison reach about 10^15, so they need 64-bit numbers.
Adding up both windows again for every day costs about n × slow steps, up to 5 × 10^9 at n = 100,000. Prefix sums give any window sum in one subtraction, so each day costs a constant number of steps and the whole task costs about n steps.