# x 6. 152. Maximum Product Subarray

152\. Maximum Product SubarrayMedium16.4K503Companies

Given an integer array `nums`, find a

subarray that has the largest product, and return *the product*.

The test cases are generated so that the answer will fit in a **32-bit** integer.

**Example 1:**

<pre><code><strong>Input: nums = [2,3,-2,4]
</strong><strong>Output: 6
</strong><strong>Explanation: [2,3] has the largest product 6.
</strong></code></pre>

**Example 2:**

<pre><code><strong>Input: nums = [-2,0,-1]
</strong><strong>Output: 0
</strong><strong>Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
</strong></code></pre>

**Constraints:**

* `1 <= nums.length <= 2 * 104`
* `-10 <= nums[i] <= 10`
* The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer.

{% embed url="<https://leetcode.com/problems/maximum-product-subarray/>" %}

### 2nd Try

> time: O(N)

> space: O(1)

```jsx
/**
 * @param {number[]} nums
 * @return {number}
 */

var maxProduct = function(nums) {
    let max = nums[0];
    let minMax = nums[0];
    let maxMax = nums[0];

    for (let i = 1; i < nums.length; i++) {
        const curr = nums[i];

        if (curr < 0) {
            const temp = minMax;
            minMax = maxMax;
            maxMax = temp;
        }

        minMax = Math.min(curr, minMax * curr);
        
        maxMax = Math.max(curr, maxMax * curr);
        max = Math.max(maxMax, max);
    }

    return max;
};
```

### 1st try

```jsx
/**
 * @param {number[]} nums
 * @return {number}
 */

let max;
var maxProduct = function(nums) {
    max = {};
    calcLocal(nums, 0, nums.length - 1);
    return max.val;
};

function calcLocal(nums, lo, hi) {
    if (lo === hi) {
        return nums[lo];
    }

    const m = lo + Math.floor((hi - lo) / 2);
    const left = calcLocal(nums, lo, m); // { left, right, total}
    const right = calcLocal(nums, m + 1, hi); // { left, right, total}
    const product = calcProduct();

    // left.right * right.left, total * total

    return { left, right, total}
}
```
