Faaez Razeen

Maximum Product Subarray

  • 2 min read
  • LC-Medium

3 years ago

Solution

From the editorial:

Let's see this problem as a problem of getting the highest combo chain. The way combo chains work is that they build on top of the previous combo chains that you have acquired. The simplest case is when the numbers in nums are all positive numbers. In that case, you would only need to keep on multiplying the accumulated result to get a bigger and bigger combo chain as you progress.

However, two things can disrupt your combo chain:

  • Zeros
  • Negative numbers
TimeSpaceExplanation
O()O()
def maxProduct(self, nums: List[int]) -> int: ans = max(nums) cur_min, cur_max = 1, 1 for num in nums: tmp = cur_max * num cur_max = max(cur_max * num, cur_min * num, num) cur_min = min(tmp, cur_min * num, num) ans = max(ans, cur_max) return ans