1010* For example, given the array [2,3,-2,4],
1111* the contiguous subarray [2,3] has the largest product = 6.
1212*
13+ * More examples:
14+ *
15+ * Input: arr[] = {6, -3, -10, 0, 2}
16+ * Output: 180 // The subarray is {6, -3, -10}
17+ *
18+ * Input: arr[] = {-1, -3, -10, 0, 60}
19+ * Output: 60 // The subarray is {60}
20+ *
21+ * Input: arr[] = {-2, -3, 0, -2, -40}
22+ * Output: 80 // The subarray is {-2, -40}
1323*
1424**********************************************************************************/
1525
1626#include < iostream>
1727#include < algorithm>
1828using namespace std ;
1929
30+ // The idea is similar with "Find the subarray wich has the largest sum"
31+ // (See: http://en.wikipedia.org/wiki/Maximum_subarray_problem)
32+ //
33+ // The only thing to note here is, maximum product can also be obtained by minimum (negative) product
34+ // ending with the previous element multiplied by this element. For example, in array {12, 2, -3, -5, -6, -2},
35+ // when we are at element -2, the maximum product is multiplication of, minimum product ending with -6 and -2.
36+ //
2037int maxProduct (int A[], int n) {
2138
39+ // To remember the max/min product for previous position
40+ int maxPrev = A[0 ], minPrev = A[0 ];
41+ // To remember the max/min product for current position
2242 int maxHere = A[0 ], minHere = A[0 ];
43+ // Overall maximum product
2344 int maxProd = A[0 ];
24- int maxPrev = A[0 ], minPrev = A[0 ];
2545
2646 for (int i=1 ; i<n; i++){
47+ // max( maxPrev * A[i], minPrev * A[i], A[i] )
2748 maxHere = max ( max ( maxPrev * A[i], minPrev * A[i] ), A[i] );
49+ // min( maxPrev * A[i], minPrev * A[i], A[i] )
2850 minHere = min ( min ( maxPrev * A[i], minPrev * A[i] ), A[i] );
51+ // Keep tracking the overall maximum product
2952 maxProd = max (maxHere, maxProd);
53+ // Shift the current max/min product to previous variables
3054 maxPrev = maxHere;
3155 minPrev = minHere;
3256 }
@@ -45,4 +69,7 @@ int main()
4569
4670 int b[] = {-1 , -1 };
4771 TEST (b);
72+
73+ int c[] = {-1 , 0 , -2 };
74+ TEST (c);
4875}
0 commit comments