1+ package com .leetcode .dynamicprogramming ;
2+
3+ import static org .junit .jupiter .api .Assertions .assertEquals ;
4+
5+ /**
6+ * Level: Medium
7+ * Link: https://leetcode.com/problems/maximum-product-subarray/
8+ * Description:
9+ * Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which
10+ * has the largest product.
11+ * <p>
12+ * Example 1:
13+ * Input: [2,3,-2,4]
14+ * Output: 6
15+ * Explanation: [2,3] has the largest product 6.
16+ * <p>
17+ * Example 2:
18+ * Input: [-2,0,-1]
19+ * Output: 0
20+ * Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
21+ *
22+ * @author rampatra
23+ * @since 2019-08-18
24+ */
25+ public class MaximumProductSubArray {
26+
27+ /**
28+ * The approach is similar to {@link MaximumSubArray} where we update maxUntilIndex only if multiplying the current
29+ * number to the product of of all numbers until index produces a larger product and if not make maxUntilIndex the
30+ * current number. The only twist here is that we keep two such variables, one for max and one for min, and that's
31+ * because the product of two negatives gives us a positive number.
32+ * <p>
33+ * Runtime: <a href="https://leetcode.com/submissions/detail/252751578/">1 ms</a>.
34+ *
35+ * @param nums
36+ * @return
37+ */
38+ public static int maxProduct (int [] nums ) {
39+ int maxProd = nums [0 ];
40+ int maxUntilIndex = nums [0 ];
41+ int minUntilIndex = nums [0 ];
42+
43+ for (int i = 1 ; i < nums .length ; i ++) {
44+ if (nums [i ] >= 0 ) {
45+ maxUntilIndex = Math .max (nums [i ], maxUntilIndex * nums [i ]);
46+ minUntilIndex = Math .min (nums [i ], minUntilIndex * nums [i ]);
47+ } else {
48+ int prevMaxUntilIndex = maxUntilIndex ;
49+ maxUntilIndex = Math .max (nums [i ], minUntilIndex * nums [i ]); // when current number is -ve then multiply with minUntilIndex to get the max as product of two negatives is a positive
50+ minUntilIndex = Math .min (nums [i ], prevMaxUntilIndex * nums [i ]);
51+ }
52+
53+ maxProd = Math .max (maxProd , maxUntilIndex );
54+ }
55+
56+ return maxProd ;
57+ }
58+
59+ public static void main (String [] args ) {
60+ assertEquals (24 , maxProduct (new int []{-2 , 3 , -4 }));
61+ }
62+ }
0 commit comments