You 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
.
乘积小于K的子数组。题目即是题意,也是比较经典的滑动窗口的题。一开始我试图用prefix sum做后来觉得没必要,滑动窗口的思路即可解决问题。唯一需要注意的是乘积是大于等于K。解释一下代码15行为什么start <= end 因为有可能子数组里面只有一个元素,而且这个元素小于K。至于为什么res +=的部分最后还要+ 1,是因为right和left都是坐标,如果两者在相同的位置上的话,res就等于0了,故而需要额外 + 1。
时间O(n)
空间O(1)
Java实现
1 class Solution { 2 public int numSubarrayProductLessThanK(int[] nums, int k) { 3 // corner case 4 if (nums == null || nums.length == 0) { 5 return 0; 6 } 7 8 // normal case 9 int product = 1; 10 int left = 0; 11 int right = 0; 12 int res = 0; 13 while (right < nums.length) { 14 product *= nums[right]; 15 while (left <= right && product >= k) { 16 product /= nums[left]; 17 left++; 18 } 19 res += right - left + 1; 20 right++; 21 } 22 return res; 23 } 24 }