[leetcode]Maximum Product Subarray

This problem gives an array and asks for the maximum product of a subarray, considering positive numbers, negative numbers, and zeros. The hint suggests computing a max and min for each value, then using them to generate the maximum and minimum including the current element. I used a simulation approach instead: multiply all numbers together — if the product is positive, it’s the maximum; if negative, compare the results of dropping the leftmost or rightmost negative number. To handle zeros, first split the array by zeros.

 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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class Solution {
public:
    int maxProductNoZero(vector<int>& nums) {
        int max = 1;
        int left = nums.size();
        int right = -1;
        for (int i = 0; i < nums.size(); i++) {
           max *= nums[i];
           if (nums[i] < 0 && i < left) {
              left = i;
           }
            if (nums[i] < 0 && i > right) {
              right = i;
           }
        }
        if (max < 0 && nums.size() > 1) {
            int max_left = 1;
            for (int i = left + 1; i < nums.size(); i++) {
                max_left *= nums[i];
            }
            int max_right = 1;
            for (int i = 0; i < right; i++) {
                max_right *= nums[i];
            }
            max = max_left > max_right ? max_left : max_right;
        }
        return max;
    }

    int maxProduct(vector<int>& nums) {
        int max = nums[0];
        vector<int> zero;
        zero.clear();
        zero.push_back(-1);
        for (int i = 0; i < nums.size(); i++) {
            if (max < nums[i]) {
               max = nums[i];
            }
            if (0 == nums[i]) {
               zero.push_back(i);
            }
        }
        zero.push_back(nums.size());
        for (int i = 0; i < zero.size() - 1; i++) {
            if (zero[i + 1] - 1  >= zero[i] + 1) {
                vector<int> sub;
                sub.clear();
                for (int j = zero[i] + 1; j <= zero[i + 1] - 1; j++) {
                    sub.push_back(nums[j]);
                }
                int tmp = maxProductNoZero(sub);
                if (tmp > max) max = tmp;
            }
        }
        return max;
    }
};