713. Subarray Product Less Than K
Use a window to keep the maximum length of subarrays where product of the subarray is less than K.
Every time we add a item to the right of the window, there will be windowLen of new subarrays ending with the last item.
So the number of subarrays will add windowLen ( which is right - left + 1
) every time we slide right.
Time complexity: O(n)
1 | class Solution { |
The idea is to store the prefix product of the array, and then for each starting position i, we use binary search to find a end position where the prefix[right] / prefix[left] < K
However, this only works because the prefix product of the array is in ascending order according to the contains 1 <= nums[i] <= 1000
.
But we can also see that is is not possible to calculate the prefix product directly because it will cause overflow. The number might be potentially too large.
That’s where the Logarithm comes to use.
$$
log(a*b) = log(a) + log(b)
$$
$$
if \space a = b, then \space log(a) = log(b)
$$
So the prefix product can be transform to sum format:
$$
prefix[i] = nums[0] \times nums[1] \times \dots \times nums[i] \\
\Rightarrow log(prefix[i]) = log(nums[0] \times nums[1] \times \dots \times nums[i]) \\
\Rightarrow log(prefix[i]) = log(nums[0]) + log(nums[1]) + \dots + log(nums[i])
$$
Time complexity: O(n log(n))
1 | class Solution { |