Back to Dashboard

Subarray Product Less Than K

Hard

Problem 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;
    }
}

Status

Solved

Complexity

Time
O(n)
Space
O(1)

Tags

ArraySliding Window

Date

2026-02-21
View Problem Source