Your are given an array of positive integers nums.
Count and print the number of (contiguous) subarrays where the product of all the elements in the subarray is less than k.
Example 1:
Input: nums = [10, 5, 2, 6], k = 100
Output: 8
Explanation: The 8 subarrays that have product less than 100 are: [10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6].
Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k.
Note:
- 0 < nums.length <= 50000.
- 0 < nums[i] < 1000.
- 0 <= k < 10^6.
Solution
- 因为已知所有的数都是
positive integers
,且要求得到连续的子序列。那么可以用Two Pointer
来得到一个子序列。 - 当当前子序列
(left ~ right)
的所有数的乘积满足条件,即product < k
时,那么可以得到left - right
之间,就有right - left + 1
个子序列满足条件; 然后向右移动right pointer
,继续找子序列。 - 当当前子序列不满足条件,
product >= k
时,向右移动left pointer
,从而使子序列的乘积变小,看是否能够满足条件。 - 例如题目,[10, 5, 2, 6],
left - right : 满足的子序列/ 个数
[10]: [10] / 1
[10, 5]: [10, 5], [5] / 2
[5, 2]: [5, 2], [2] / 2
[5, 2, 6] : [5, 2, 6], [2, 6], [6] / 3
所以总个数为 1 + 2 + 2 + 3 = 8
class Solution {
public int numSubarrayProductLessThanK(int[] nums, int k) {
int product = 1;
int result = 0;
int left = 0;
int right = 0;
for (; right < nums.length; right ++)
{
product *= nums [right];
while (left <= right && product >= k)
{
product = product / nums [left];
left ++;
}
result += right - left + 1;
}
return result;
}
}