713 Subarray Product Less Than K
Your are given an array of positive integersnums
.
Count and print the number of (contiguous) subarrays where the product of all the elements in the subarray is less thank
.
Example 1:
Note:
0 < nums.length <= 50000.
0 < nums[i] < 1000.
0 <= k < 10^6.
The Idea: Keep two pointers, left and right that represent the a current product that is less than k. The right point will always increment 1 at a time and multiply the underlying number, and the left point will adjust the window by moving left and dividing the underlying number to represent the subarray product. The distance between left and right (length of the subarray) will also represent the number of subarrays that have a product less than k. To understand this consider our current subarray to be [5,2]
, and the right point just added [6]
. The product here is 60
, and suppose k = 100
. The total number of subarrays that can represented here is 3
because [6]
we obtain the new subarrays: [6]
, [2,6]
, and [5,2,6]
. that is, the new element that the right pointed added can become a part of every element before it in the subarray product, including just itself. Another example: prev: [5,2,4]
and [6]
, we obtain 4 new subarrays [6]
, [4,6]
, [2,4,6]
, and [5,2,4,6]
.
Complexity: O(n) time and constant space
Limited n^2 Solution
Last updated