Given a fixed-size array containing
One approach is to generate all possible sub-arrays and return the maximum product after evaluating the product of each sub-array. However, this is a very inefficient solution as it will take
In this Answer, we'll explore how a more efficient solution can be implemented for this task, which takes
To efficiently solve this problem, we need to keep track of 3 products while iterating through the array. The products are as follows:
The current maximum product (
The current minimum product (
The overall largest product encountered (
The algorithm is as follows:
Initialize
Begin iterating the array.
If the current element is negative, swap the values of
Update
Once the array is completely traversed, return
The example below visually demonstrates how this algorithm works:
The code below implements the logic discussed above in C++ and Python:
The important lines in the code are explained below:
Lines 6 – 8: We initialize prod_max
, prod_min
and overall_max
to arr[0]
.
Lines 20 – 27: We update prod_max
such that prod_max
is max(arr[i], arr[i] * prod_max)
.
Lines 30 – 37: We update prod_min
such that prod_min
is min(arr[i], arr[i] * prod_min)
.
Lines 40 – 47: We update overall_max
such that overall_max
is max(overall_max, arr[i] * overall_max)
.