Skip to content

152. Maximum Product Subarray 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
 public:
  int maxProduct(vector<int>& nums) {
    int ans = nums[0];
    int dpMin = nums[0];  // the minimum so far
    int dpMax = nums[0];  // the maximum so far

    for (int i = 1; i < nums.size(); ++i) {
      const int num = nums[i];
      const int prevMin = dpMin;  // dpMin[i - 1]
      const int prevMax = dpMax;  // dpMax[i - 1]
      if (num < 0) {
        dpMin = min(prevMax * num, num);
        dpMax = max(prevMin * num, num);
      } else {
        dpMin = min(prevMin * num, num);
        dpMax = max(prevMax * num, num);
      }
      ans = max(ans, dpMax);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
  public int maxProduct(int[] nums) {
    int ans = nums[0];
    int dpMin = nums[0]; // the minimum so far
    int dpMax = nums[0]; // the maximum so far

    for (int i = 1; i < nums.length; ++i) {
      final int num = nums[i];
      final int prevMin = dpMin; // dpMin[i - 1]
      final int prevMax = dpMax; // dpMax[i - 1]
      if (num < 0) {
        dpMin = Math.min(prevMax * num, num);
        dpMax = Math.max(prevMin * num, num);
      } else {
        dpMin = Math.min(prevMin * num, num);
        dpMax = Math.max(prevMax * num, num);
      }
      ans = Math.max(ans, dpMax);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
  def maxProduct(self, nums: list[int]) -> int:
    ans = nums[0]
    dpMin = nums[0]  # the minimum so far
    dpMax = nums[0]  # the maximum so far

    for i in range(1, len(nums)):
      num = nums[i]
      prevMin = dpMin  # dpMin[i - 1]
      prevMax = dpMax  # dpMax[i - 1]
      if num < 0:
        dpMin = min(prevMax * num, num)
        dpMax = max(prevMin * num, num)
      else:
        dpMin = min(prevMin * num, num)
        dpMax = max(prevMax * num, num)

      ans = max(ans, dpMax)

    return ans