Monitoring~18 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-152kadane
A monitoring system passes a signal through a chain of stages. Each stage multiplies the signal by an integer gain from -2 to 2. A gain of 0 blocks the signal, and a negative gain flips its sign.
Engineers want the strongest consecutive group of stages: the run whose gains multiply to the largest product. The chain can hold 100,000 stages, but at most 50 of them have a gain of 2 or -2.
Write best_gain_product(gains).
gains[i] is the integer gain of stage i, from -2 to 2.Input: gains = [2, -1, -2, 1, 0, 2, -2]
Output: 4The best run is the first four stages: 2 × (-1) × (-2) × 1 = 4.
Keep the biggest and the smallest product of a run that ends at each stage.
| Stage | Gain | biggest_here | smallest_here | best_so_far |
|---|---|---|---|---|
| 0 | 2 | 2 | 2 | 2 |
| 1 | -1 | -1 | -2 | 2 |
| 2 | -2 | 4 | -2 | 4 |
| 3 | 1 | 4 | -2 | 4 |
| 4 | 0 | 0 | 0 | 4 |
| 5 | 2 | 2 | 0 | 4 |
| 6 | -2 | 0 | -4 | 4 |
At stage 2 the gain is negative, so the smallest product -2 turns into the biggest product 4. At stage 4 the zero resets both.
Input: gains = [-2]
Output: -2A run needs at least one stage, so the answer is the single gain -2.
Input: gains = [0, -1, 0]
Output: 0Every run with a zero multiplies to 0, and the run of one stage with gain -1 is worse.
1 ≤ gains.length ≤ 100,000 (stages in the chain)-2 ≤ gains[i] ≤ 2 (gain of a stage)gains[i] = 2 or gains[i] = -2Multiplying every run from every start stage costs about n × n / 2 products, which is 5,000,050,000 at n = 100,000. A single pass costs about n steps. The promise about at most 50 gains of size 2 keeps every product below 2^50, so 64-bit integers do not overflow.