Minimum Product of K Consecutive
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
Algorithm Flow
Solution Approach
Use a sliding window to maintain the product incrementally and track the minimum, handling zeros by recomputing.
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
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;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
