Description
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
1. 0 < nums.length <= 50000.
2. 0 < nums[i] < 1000.
3. 0 <= k < 10^6.
Solution 1(C++)
class Solution {
public:
int numSubarrayProductLessThanK(vector<int>& nums, int k) {
if (k <= 1) return 0;
int n = nums.size(), prod = 1, ans = 0, left = 0;
for (int i = 0; i < n; i++) {
prod *= nums[i];
while (prod >= k) prod /= nums[left++];
ans += i - left + 1;
}
return ans;
}
};
后续更新
2018-5-12与之类似的题目可参考:
算法分析
这一道题,我其实最应该注意的关键词是:the number of (contiguous) subarrays。这两个词一出来,就可以应该有思路:参考:
LeetCode-560. Subarray Sum Equals K;
LeetCode-795. Number of Subarrays with Bounded Maximum;
所以这也是基本题型的变种。我就不罗嗦了,基本想法与上面两道题是类似的。
程序分析
略。