Computer scienceAlgorithms and data structuresAlgorithmsPrinciples and techniques

Sliding window

Theory

Maximum product

Report a typo

You have an array of integers (positive and non-zero) and an integer K(K>0)K (K > 0). Your job is to find the largest product of KK consecutive elements in the array. For example, with the array [1,8,5,2,9,4][1, 8, 5, 2, 9, 4] and K=3K = 3, the largest product of 33 consecutive elements is 529=905 * 2 * 9 = 90.

Here is the pseudocode to solve the problem. Please complete it.

(How can you efficiently solve the problem if the array also contains negative integers and zeros? Please provide your solution in the comment box below.)

Fill in the gaps with the relevant elements
function maxProductSubarray(array, K):
    // Initialize the start of the window and the product of the first window
    start = 1
    windowProduct = product of first K elements in the array

    // Initialize maxProduct to store the maximum product of a subarray of size K
    maxProduct = windowProduct

    // Iterate through the array starting from the (K+1)th element
    for end from K+1 to length(array):
        windowProduct = 
        maxProduct = 
        

    // Return the maximum product of a subarray of size K
    return maxProduct
(windowProduct * array[start]) / array[end]start++(windowProduct * array[end]) / array[start]max(maxProduct, windowProduct)

Create a free account to access the full topic