Leetcode: Maximum Product Subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest product.

For example, given the array [2,3,-2,4],

the contiguous subarray [2,3] has the largest product = 6.

Leetcode出了新题,连续子数组最大乘积,跟连续子数组最大和有点类似。必定是O(n)的算法啊,超过这个时间复杂度的就不用考虑了。

整数相乘,除非正负号变了否则必定一直增加。所以可以记录下第一个负数的位置,如果后面连乘积是负数,那么计算从第一个负数之后开始的连乘积。还得注意0的情况,这时候第一个负数要重新算起。

class Solution {
public:
    int maxProduct(int A[], int n) {
        if (n == 0) {
            return 0;
        }
        
        int max_product = A[0];
        int products = A[0];
        int min_products = A[0] < 0 ? A[0] : 1;
        for (int i = 1; i < n; ++i) {
            if (products == 0) {
                products = 1;
                min_products = 1;
            }
            
            products *= A[i];
            if (products > max_product) {
                max_product = products;
            }
            else if (products < 0) {
                if (min_products == 1) {
                    min_products = products;    
                }
                else {
                    max_product = max(max_product, products / min_products);
                }
            }
        }
        
        return max_product;
    }
};

DP方式,简单易懂。

class Solution {
public:
    int maxProduct(vector<int>& nums) {
        if (nums.empty()) {
            return 0;
        }
        
        int curMax = nums[0];
        int curMin = nums[0];
        int result = nums[0];
        for (int i = 1; i < nums.size(); ++i) {
            int tmp = curMax;
            curMax = max(nums[i], max(curMax * nums[i], curMin * nums[i]));
            curMin = min(nums[i], min(tmp * nums[i], curMin * nums[i]));
            result = max(result, curMax);
        }
        
        return result;
    }
};


你可能感兴趣的:(LeetCode,算法)