- Subarray Product Less Than K
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.
这题因为有空间限制,不能用预处理记下i,j之间的乘积,也不能用DP,因为会用到二维数组。
解法1:
我的解法是每次从i往左动,若product>k退出,否则count++。
这个算法会有冗余计算。但总的复杂度还是O(n^2)。
class Solution {
public:
/**
* @param nums: an array
* @param k: an integer
* @return: the number of subarrays where the product of all the elements in the subarray is less than k
*/
int numSubarrayProductLessThanK(vector<int> &nums, int k) {
int n = nums.size();
if (n == 0) return 0;
long long product = 1;
for (int i = 0; i < n; ++i) {
helper(nums, i, k);
}
return count;
}
private:
int count = 0;
void helper(vector<int> & nums, int index, int k) {
long long product = 1;
for (int i = index; i >= 0; i--) {
if (nums[i] > k) break;
product *= nums[i];
if (product < k) {
count++;
} else {
break;
}
}
}
};
解法2:
网上看到一个很牛的解法。
https://www.cnblogs.com/grandyang/p/7753959.html
class Solution {
public:
/**
* @param nums: an array
* @param k: an integer
* @return: the number of subarrays where the product of all the elements in the subarray is less than k
*/
int numSubarrayProductLessThanK(vector<int> &nums, int k) {
int n = nums.size();
if (n == 0|| k == 0) return 0;
long long product = 1;
int count = 0;
int left = 0, right = 0;
while (right < n) {
product *= nums[right];
while (product >= k) {
product /= nums[left];
left++;
}
count += right - left + 1;
right++;
}
return count;
}
};
三刷: 套用sliding window 模板
class Solution {
public:
int numSubarrayProductLessThanK(vector<int>& nums, int k) {
if (k == 0) return 0;
int n = nums.size();
int prod = 1, res = 0;
int left = 0, right = 0;
while (right < n) {
prod *= nums[right];
right++;
while (left < right && prod >= k) { //注意这里是left<right 不是<=
prod /= nums[left];
left++;
}
res += right - left;
//[10,5,2,6],k=100,
//right=1,left=0,prod=10, 可行窗口是[10],res+=1,即加入[10]
//right=2,left=0,prod=50, 可行窗口是[10,5],res+=2,即加入[5],[10,5]
//right=3,left=0,prod=100, 缩小窗口,prod=100/10=10,left=1, 可行窗口是[5,2],res+=2,即加入[2],[5,2]
//right=4,left=1,prod=60,可行窗口是[5,2,6],res+=3,即加入[6],[2,6],[5,2,6]
}
return res;
}
};