Subarray Product Less than K
- Lintcode : 1075 / Leetcode : 713
- Level : Medium
Problem
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
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.
Example 2:
Input: nums = [5,10,2], k = 10
Output: 2
Explanation:
Only [5] and [2].
Notice
0 < nums.length <= 50000.
0 < nums[i] < 1000.
0 <= k < 10^6.
Concept & Algorithm
Time Complexity & Space Complexity
time : O(n)
space: O(1)
Answer
class Solution {
public:
int numSubarrayProductLessThanK(vector<int> &nums, int k) {
int n = nums.size();
if (k <= 1 || n == 0) return 0;
int count = 0, left = 0, product = 1;
for (int i = 0;i < n; i++) {
product = product * nums[i];
while (product >= k)
product /= nums[left++];
count += i - left + 1;
}
return count;
}
};
沒有留言:
張貼留言