/ Data Structure and Algorithms  

Leetcode 152. Maximum Product Subarray

Question



Given an array, find the continuous sub-array which have the maximum multiplication.

Similar Questions

Solution

We first define an array dpMax, and use dpMax[i] to denote the value of the largest product with the sub-array ending with the i-th element, that is, this array must contain the i-th element.

Then dpMax[i] has several possible values:

  • When nums[i] >= 0 and dpMax[i-1] > 0, dpMax[i] = dpMax[i-1] * nums[i]
  • When nums[i] >= 0 and dpMax[i-1] < 0, if it is multiplied by the previous number, it will become a negative number, so dpMax[i] = nums[i]
  • When nums[i] < 0, if the previous multiplication result is a large negative number, it will become a larger number if it is multiplied with the current negative number. So we also need an array dpMin to record the the smallest product value with sub-array ending in the i-th element, .
    • When dpMin[i-1] < 0, dpMax[i] = dpMin[i-1] * nums[i]
    • When dpMin[i-1] >= 0, dpMax[i] = nums[i]

Of course, how to find dpMin is actually the same as the process of finding dpMax above.

According to the above analysis, we need to have a lot of if else to determine different situations, here we can use a trick.

We noticed that the values of dpMax[i] above are nothing more than three types

  • dpMax[i-1] * nums[i]
  • dpMin[i-1] * nums[i]
  • nums[i]

So when we update, we don’t need to distinguish the current situation, we only need to choose the largest one from the three values:

1
dpMax[i] = max(dpMax[i-1] * nums[i], dpMin[i-1] * nums[i], nums[i]);

The same applis for dpMin[i]:

1
dpMin[i] = min(dpMax[i-1] * nums[i], dpMin[i-1] * nums[i], nums[i]);

Also notice that when updating dp[i], we only used dp[i-1], and the previous information would not be used. So we don’t need an array at all, we just need a variable to repeat overwrite and update.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public int maxProduct(int[] nums) {
int result = 0;

if (nums.length == 0) {
return result;
}

// need to keep a record of max product and min product ending at index i
// want to keep min because if current < 0, we want min * current become large if min < 0
int preMax = nums[0];
int preMin = nums[0];

result = preMax;

for (int i = 1; i < nums.length; i++) {
// 3 conditions
// 1 - nums[i] >= 0 and preMax > 0
// then we update preMax = preMax * num[i]
// 2 - nums[i] >= 0 and preMax < 0
// then we update preMax = nums[i]
// 3 - nums[i] < 0
// then if preMin < 0, then update preMax = preMin * nums[i]
// else preMax = nums[i]
// we can see there are 3 possible values: preMax * num[i], nums[i], preMin * nums[i]
int tempMax = preMax;

preMax = Math.max(preMax * nums[i], Math.max(nums[i], preMin * nums[i]));
preMin = Math.min(tempMax * nums[i], Math.min(nums[i], preMin * nums[i]));

result = Math.max(preMax, result);
}

return result;
}