[LeetCode] 152. Maximum Product Subarray 求最大子数组乘积

Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.

Example 1:

Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.

Example 2:

Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.

53. Maximum Subarray 的变形,求和的时候,遇到0不会改变最大值,遇到负数也只是会减小最大值。而在求最大子数组乘积,遇到0会使整个乘积为0,遇到负数会使最大乘积变成最小乘积。

解法:DP,用2个dp数组分别记录到i时的最大乘积和最小乘积,因为下一个数字如果为负数就可以把最小的乘积是负的变成正的最大值。

Java:

public int maxProduct(int[] A) {
   assert A.length > 0;
   int max = A[0], min = A[0], maxAns = A[0];
   for (int i = 1; i < A.length; i++) {
      int mx = max, mn = min;
      max = Math.max(Math.max(A[i], mx * A[i]), mn * A[i]);
      min = Math.min(Math.min(A[i], mx * A[i]), mn * A[i]);
      maxAns = Math.max(max, maxAns);
   }
   return maxAns;
}

Python:

class Solution:
    # @param A, a list of integers
    # @return an integer
    def maxProduct(self, A):
        global_max, local_max, local_min = float("-inf"), 1, 1
        for x in A:
            local_max, local_min = max(x, local_max * x, local_min * x), min(x, local_max * x, local_min * x)
            global_max = max(global_max, local_max)
        return global_max

Python:

class Solution2:
    # @param A, a list of integers
    # @return an integer
    def maxProduct(self, A):
        global_max, local_max, local_min = float("-inf"), 1, 1
        for x in A:
            local_max = max(1, local_max)
            if x > 0:
                local_max, local_min = local_max * x, local_min * x
            else:
                local_max, local_min = local_min * x, local_max * x
            global_max = max(global_max, local_max)
        return global_max  

Python: wo

class Solution(object):
    def maxProduct(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        dp1 = [0] * len(nums)
        dp1[0] = nums[0]
        dp2 = [0] * len(nums)
        dp2[0] = nums[0]
        res = dp1[0]
        for i in xrange(1, len(nums)):
            dp1[i] = max(dp1[i-1] * nums[i], dp2[i-1] * nums[i], nums[i])
            dp2[i] = min(dp1[i-1] * nums[i], dp2[i-1] * nums[i], nums[i])
            res = max(res, dp1[i])

        return res

C++:

class Solution {
public:
    int maxProduct(vector<int>& nums) {
        if (nums.empty()) return 0;
        int res = nums[0], mn = nums[0], mx = nums[0];
        for (int i = 1; i < nums.size(); ++i) {
            int tmax = mx, tmin = mn;
            mx = max(max(nums[i], tmax * nums[i]), tmin * nums[i]);
            mn = min(min(nums[i], tmax * nums[i]), tmin * nums[i]);
            res = max(res, mx);
        }
        return res;
    }
};

C++:

class Solution {
public:
    int maxProduct(vector<int>& nums) {
        int res = nums[0], mx = res, mn = res;
        for (int i = 1; i < nums.size(); ++i) {
            if (nums[i] > 0) {
                mx = max(mx * nums[i], nums[i]);
                mn = min(mn * nums[i], nums[i]);
            } else {
                int t = mx;
                mx = max(mn * nums[i], nums[i]);
                mn = min(t * nums[i], nums[i]);
            }
            res = max(res, mx);
        }
        return res;
    }
};

C++:

class Solution {
public:
    int maxProduct(vector<int>& nums) {
        int res = nums[0], mx = res, mn = res;
        for (int i = 1; i < nums.size(); ++i) {
            if (nums[i] < 0) swap(mx, mn);
            mx = max(nums[i], mx * nums[i]);
            mn = min(nums[i], mn * nums[i]);
            res = max(res, mx);
        }
        return res;
    }
};

C++:  

class Solution {
public:
    int maxProduct(vector<int>& nums) {
        int res = nums[0], prod = 1, n = nums.size();
        for (int i = 0; i < n; ++i) {
            res = max(res, prod *= nums[i]);
            if (nums[i] == 0) prod = 1;
        }
        prod = 1;
        for (int i = n - 1; i >= 0; --i) {
            res = max(res, prod *= nums[i]);
            if (nums[i] == 0) prod = 1;
        }
        return res;
    }
};

    

类似题目:

[LeetCode] 53. Maximum Subarray 最大子数组

原文地址:https://www.cnblogs.com/lightwindy/p/9678602.html

时间: 2024-11-05 15:49:22

[LeetCode] 152. Maximum Product Subarray 求最大子数组乘积的相关文章

Maximum Product Subarray 求最大子数组乘积

这个求最大子数组乘积问题是由最大子数组之和问题演变而来,但是却比求最大子数组之和要复杂,因为在求和的时候,遇到0,不会改变最大值,遇到负数,也只是会减小最大值而已.而在求最大子数组乘积的问题中,遇到0会使整个乘积为0,而遇到负数,则会使最大乘积变成最小乘积,正因为有负数和0的存在,使问题变得复杂了不少.. 比如,我们现在有一个数组[2, 3, -2, 4],我们可以很容易的找出所有的连续子数组,[2], [3], [-2], [4], [2, 3], [3, -2], [-2, 4], [2,

【LeetCode】Maximum Product Subarray 求连续子数组使其乘积最大

Add Date 2014-09-23 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 = 

LeetCode 152. 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. 题目标签:Array, Dynamic Programming 题目给了我们一个nu

C#解leetcode 152. 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. 分析:这个题目就是让你求连续的子数组的乘积的最大值. (1)在数组中没有0的情况下,

(Java) LeetCode 152. Maximum Product Subarray —— 乘积最大子序列

Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product. Example 1: Input: [2,3,-2,4] Output: 6 Explanation: [2,3] has the largest product 6. Example 2: Input: [-2,0,-1]

leetcode 152. Maximum Product Subarray --------- java

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. 找出最大的相乘的数字,很简单,代码还可以优化的地方很多.但是速度还可以. publi

Java for LeetCode 152 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. 解题思路: 计算连续的积最大,由于会有负数出现,因此需要用两个int表示包含num

[动态规划] leetcode 152 Maximum Product Subarray

problem:https://leetcode.com/problems/maximum-product-subarray 类似买卖股票,需要维护两个状态,当前最大数和最小数. class Solution { public: int maxProduct(vector<int>& nums) { int res = INT_MIN; int num_max = 1; int num_min = 1; for(int i = 0;i<nums.size();i++) { int

152. Maximum Product Subarray(js)

152. Maximum Product Subarray Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product. Example 1: Input: [2,3,-2,4] Output: 6 Explanation: [2,3] has the largest product