Your are given an array of positive integers nums
.java
Count and print the number of (contiguous) subarrays where the product of all the elements in the subarray is less than k
.數組
Example 1:less
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:code
0 < nums.length <= 50000
.element
0 < nums[i] < 1000
.it
0 <= k < 10^6
.io
找到全部的連續子數組,使其積小於指定值。class
遍歷數組全部元素做爲區間右端點;對於每一個右端點,找到最左側的元素,使構成的區間的積小於指定值;累加以右端點爲終點的子區間的數量。遍歷
public int numSubarrayProductLessThanK(int[] nums, int k) { int count = 0; int left = 0, product = 1; for (int right = 0; right < nums.length; right++) { product *= nums[right]; while (product >= k && left <= right) { product /= nums[left++]; } count += right - left + 1; } return count; }