Code Logo

Maximum Product of K Consecutive

Published at24 Jul 2026
Easy 0 views
Like0

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

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

Sliding window maximum product requires careful handling of zeros. When the outgoing element is zero, the product must be recomputed from scratch rather than divided.

The solution computes the product of the first k elements, then slides: divide by outgoing and multiply by incoming. If the outgoing element is zero, recompute the window product from scratch.

Edge cases include k larger than the array (return 0), an empty array (return 0), and zeros in the array (the window product becomes zero and requires special handling when sliding past a zero).

Example Input & Output

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

Algorithm Flow

Recommendation Algorithm Flow for Maximum Product of K Consecutive

Solution Approach

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

function maxProductK(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]
  maxProd = 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 > maxProd then maxProd = prod
  return maxProd

Product of first window. Slide: if outgoing is zero, recompute. Otherwise, divide by outgoing and multiply by incoming. Track maximum.

Time complexity is O(n*k) worst case, 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.max(best, prod);
        }
        return best;
    }
}