@@ -79,4 +79,53 @@ public int maxProduct2(int[] nums) {
79
79
}
80
80
81
81
82
+ /**
83
+ * https://leetcode.com/problems/maximum-product-subarray/discuss/48330/Simple-Java-code
84
+ */
85
+ public int maxProduct3 (int [] A ) {
86
+ if (A == null || A .length == 0 ) {
87
+ return 0 ;
88
+ }
89
+ int max = A [0 ], min = A [0 ], result = A [0 ];
90
+ for (int i = 1 ; i < A .length ; i ++) {
91
+ int temp = max ;
92
+ max = Math .max (Math .max (max * A [i ], min * A [i ]), A [i ]);
93
+ min = Math .min (Math .min (temp * A [i ], min * A [i ]), A [i ]);
94
+ if (max > result ) {
95
+ result = max ;
96
+ }
97
+ }
98
+ return result ;
99
+ }
100
+
101
+
102
+ /**
103
+ * https://leetcode.com/problems/maximum-product-subarray/discuss/48230/Possibly-simplest-solution-with-O(n)-time-complexity
104
+ */
105
+ public int maxProduct4 (int A []) {
106
+ // store the result that is the max we have found so far
107
+ int r = A [0 ];
108
+
109
+ // imax/imin stores the max/min product of
110
+ // subarray that ends with the current number A[i]
111
+ for (int i = 1 , imax = r , imin = r ; i < A .length ; i ++) {
112
+ // multiplied by a negative makes big number smaller, small number bigger
113
+ // so we redefine the extremums by swapping them
114
+ if (A [i ] < 0 ) {
115
+ int t = imax ;
116
+ imax = imin ;
117
+ imin = t ;
118
+ }
119
+
120
+ // max/min product for the current number is either the current number itself
121
+ // or the max/min by the previous number times the current one
122
+ imax = Math .max (A [i ], imax * A [i ]);
123
+ imin = Math .min (A [i ], imin * A [i ]);
124
+
125
+ // the newly computed max value is a candidate for our global result
126
+ r = Math .max (r , imax );
127
+ }
128
+ return r ;
129
+ }
130
+
82
131
}
0 commit comments