Back to Dashboard
Subarray Product Less Than K
HardProblem Statement
Given an array of positive numbers and a positive number k, find the maximum sum of any contiguous subarray of size k.
Examples
Example 1:
- Input:
nums = [1, 2, 3, 4], k = 2 - Output:
6
Approach 1 Sliding Window:
class Solution {
public int numSubarrayProductLessThanK(int[] nums, int k) {
int product = 1, windowStart = 0, res = 0;
for (int windowEnd = 0; windowEnd < nums.length; windowEnd ++) {
product *= nums[windowEnd];
while (product >= k && windowStart <= windowEnd) {
product /= nums[windowStart];
windowStart ++;
}
res += windowEnd - windowStart + 1;
}
return res;
}
}