Payments app~25 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-713sliding-window-variable
A payments app scores every transfer in a batch with a risk factor, a whole number of at least 1. A higher factor marks a riskier transfer.
Risk compounds along a stretch of consecutive transfers: the risk of the stretch is the product of its factors. The fraud team has a limit, and a stretch is acceptable when its product is strictly below the limit.
They want to know how many acceptable stretches the batch holds. Stretches may overlap, and each pair of first and last transfer counts once.
Write count_small_products(factors, limit).
factors[i] is the risk factor of transfer i, a whole number from 1 to 1000.i to j with i ≤ j.factors[i] × ... × factors[j] < limit.Input: factors = [2, 3, 4, 1, 6, 2], limit = 30
Output: 16The window keeps the product of its factors. When a factor joins and the product reaches the limit, factors leave from the left until it is below the limit again. Every stretch that ends at right and starts at left or later is acceptable, so add right - left + 1.
| right | Joins | Product after the join | Leaves | Product after | left after | New stretches | Total |
|---|---|---|---|---|---|---|---|
| 0 | 2 | 2 | none | 2 | 0 | 1 | 1 |
| 1 | 3 | 6 | none | 6 | 0 | 2 | 3 |
| 2 | 4 | 24 | none | 24 | 0 | 3 | 6 |
| 3 | 1 | 24 | none | 24 | 0 | 4 | 10 |
| 4 | 6 | 144 | 2, 3 | 24 | 2 | 3 | 13 |
| 5 | 2 | 48 | 4 | 12 | 3 | 3 | 16 |
At right = 4 the product 144 is not below 30. Removing the 2 gives 72 and removing the 3 gives 24, which is below 30.
Input: factors = [5, 5, 5], limit = 1
Output: 0Every product is at least 1, so none is below 1.
Input: factors = [1, 1, 1], limit = 5
Output: 6Every product is 1, so all six stretches are acceptable.
1 ≤ factors.length ≤ 100,000 (transfers in the batch)1 ≤ factors[i] ≤ 1000 (risk factor)1 ≤ limit ≤ 10^9Starting at every transfer and multiplying until the product reaches the limit is O(n^2) in the worst case. When all factors are 1 and the limit is 2, no start stops early, and that is about 5 × 10^9 steps. Aim for O(n).
The count can reach n × (n + 1) / 2 = 5,000,050,000. That is beyond a 32-bit integer, so use a 64-bit type (long in Java, long long in C++). The window's product stays below limit × 1000, which is at most 10^12, so it needs 64 bits too.