Algorithm
Problem Name: 713. Subarray Product Less Than K
Given an array of integers nums
and an integer k
, return the number of contiguous subarrays where the product of all the elements in the subarray is strictly 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.
Example 2:
Input: nums = [1,2,3], k = 0 Output: 0
Constraints:
1 <= nums.length <= 3 * 104
1 <= nums[i] <= 1000
0 <= k <= 106
Code Examples
#1 Code Example with C++ Programming
Code -
C++ Programming
class Solution {
public:
int numSubarrayProductLessThanK(vector<int>& nums, int k) {
int count = 0, product = 1;
for(int i = 0, j = 0, pre = 0; j < nums.size(); i++, pre = j, j = max(i, j)){
while(j < nums.size() && product * nums[j] < k) product *= nums[j++];
count += (long)(j - pre) * (1 + (j - pre)) / 2 + (j - pre) * (pre - i);
product = max(product / nums[i], 1);
}
return count;
}
};
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with Java Programming
Code -
Java Programming
class Solution {
public int numSubarrayProductLessThanK(int[] nums, int k) {
if (k <= 1) {
return 0;
}
int prod = 1;
int ans = 0;
int left = 0;
for (int right = 0; right < nums.length; right++) {
prod *= nums[right];
while (prod >= k) {
prod /= nums[left++];
}
ans += right - left + 1;
}
return ans;
}
}
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with Javascript Programming
Code -
Javascript Programming
const numSubarrayProductLessThanK = function(nums, k) {
if (k == 0) return 0
let cnt = 0
let pro = 1
for (let i = 0, j = 0, len = nums.length; j < len; j++) {
pro *= nums[j]
while (i <= j && pro >= k) {
pro /= nums[i++]
}
cnt += j - i + 1
}
return cnt
}
Copy The Code &
Try With Live Editor
Input
#4 Code Example with Python Programming
Code -
Python Programming
class Solution:
def numSubarrayProductLessThanK(self, nums, k):
l, res, cur = 0, 0, 1
for i in range(len(nums)):
cur *= nums[i]
while cur >= k and l < i: l, cur = l + 1, cur // nums[l]
if cur < k: res += i - l + 1
return res
Copy The Code &
Try With Live Editor
Input
#5 Code Example with C# Programming
Code -
C# Programming
namespace LeetCode
{
public class _0713_SubarrayProductLessThanK
{
public int NumSubarrayProductLessThanK(int[] nums, int k)
{
if (k <= 1) return 0;
int prod = 1, result = 0, left = 0;
for (int right = 0; right < nums.Length; right++)
{
prod *= nums[right];
while (prod >= k)
prod /= nums[left++];
result += right - left + 1;
}
return result;
}
}
}
Copy The Code &
Try With Live Editor
Input
Output