Skip to content

Latest commit

 

History

History
83 lines (61 loc) · 2.15 KB

File metadata and controls

83 lines (61 loc) · 2.15 KB

中文文档

Description

Given an integer array nums, find a contiguous non-empty subarray within the array that has the largest product, and return the product.

It is guaranteed that the answer will fit in a 32-bit integer.

A subarray is a contiguous subsequence of the array.

 

Example 1:

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

Example 2:

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

 

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.

Solutions

Python3

class Solution:
    def maxProduct(self, nums: List[int]) -> int:
        maxf = minf = nums[0]
        res, n = nums[0], len(nums)
        for i in range(1, n):
            p, q = maxf, minf
            maxf = max(nums[i], p * nums[i], q * nums[i])
            minf = min(nums[i], p * nums[i], q * nums[i])
            res = max(res, maxf)
        return res

Java

class Solution {
    public int maxProduct(int[] nums) {
        int maxf = nums[0], minf = nums[0];
        int res = nums[0], n = nums.length;
        for (int i = 1; i < n; ++i) {
            int p = maxf, q = minf;
            maxf = Math.max(nums[i], Math.max(p * nums[i], q * nums[i]));
            minf = Math.min(nums[i], Math.min(p * nums[i], q * nums[i]));
            res = Math.max(res, maxf);
        }
        return res;
    }
}

...