Code Logo

Minimum Product of K Consecutive

Published at24 Jul 2026
Easy 1 views
Like0

Given an array of integers and a window size k, find the minimum product among all subarrays of length k. Return the minimum product.

For example, in [2, 3, -2, 4] with k=3, windows: [2,3,-2] product=-12, [3,-2,4] product=-24. Minimum product is -24. With k=2: [2,3]=6, [3,-2]=-6, [-2,4]=-8. Minimum is -8.

Finding the minimum product with sliding windows is similar to minimum sum but uses multiplication instead of addition. Products can be negative, zero, or positive.

The solution computes the product of the first k elements, then slides the window: divide by the outgoing element and multiply by the incoming element, tracking the minimum product.

Edge cases include k larger than the array (return 0), an empty array (return 0), and zero values in the array (the product becomes zero and dividing by zero must be handled by recomputing the window from scratch).

Example Input & Output

Example 1
Input
[-1,2,-3],2
Output
-6
Example 2
Input
[5,4,3,2,1],3
Output
6
Example 3
Input
[],2
Output
0
Example 4
Input
[2,3,4],2
Output
6
Example 5
Input
[1],1
Output
1

Algorithm Flow

Recommendation Algorithm Flow for Minimum Product of K Consecutive

Solution Approach

Use a sliding window to maintain the product incrementally and track the minimum, handling zeros by recomputing.

function minProductK(arr, k)
  if k > length(arr) or length(arr) == 0 then return 0
  prod = 1
  for i = 0 to k - 1
    prod = prod * arr[i]
  minProd = prod
  for i = k to length(arr) - 1
    if arr[i - k] == 0
      prod = 1
      for j = i - k + 1 to i
        prod = prod * arr[j]
    else
      prod = prod / arr[i - k] * arr[i]
    if prod < minProd then minProd = prod
  return minProd

Product of first window. Slide: if the outgoing element is zero, recompute the window from scratch. Otherwise, divide by outgoing and multiply by incoming. Track the minimum product.

Time complexity is O(n*k) worst case with zeros, O(n) average. Space complexity is O(1).

Best Answers

java
class Solution {
    public int solution(int[] nums, int k) {
        if (nums.length == 0 || k > nums.length) return 0;
        int prod = 1;
        for (int i = 0; i < k; i++) prod *= nums[i];
        int best = prod;
        for (int i = k; i < nums.length; i++) {
            if (nums[i-k] == 0) {
                prod = 1;
                for (int j = i-k+1; j <= i; j++) prod *= nums[j];
            } else {
                prod = prod / nums[i-k] * nums[i];
            }
            best = Math.min(best, prod);
        }
        return best;
    }
}