Skip to content

Latest commit

 

History

History
135 lines (92 loc) · 3.57 KB

maximum-product-subarray.md

File metadata and controls

135 lines (92 loc) · 3.57 KB

152. Maximum Product Subarray - 乘积最大子数组

Tags - 题目标签

Description - 题目描述

EN:

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:

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.

ZH-CN:

给你一个整数数组 nums ,请你找出数组中乘积最大的非空连续子数组(该子数组中至少包含一个数字),并返回该子数组所对应的乘积。

测试用例的答案是一个 32-位 整数。

子数组 是数组的连续子序列。

 

示例 1:

输入: nums = [2,3,-2,4]
输出: 6
解释: 子数组 [2,3] 有最大乘积 6。

示例 2:

输入: nums = [-2,0,-1]
输出: 0
解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。

 

提示:

  • 1 <= nums.length <= 2 * 104
  • -10 <= nums[i] <= 10
  • nums 的任何前缀或后缀的乘积都 保证 是一个 32-位 整数

Link - 题目链接

LeetCode - LeetCode-CN

Latest Accepted Submissions - 最近一次 AC 的提交

Language Runtime Memory Submission Time
golang 4 ms 3.8 MB 2023/01/09 21:55
func maxProduct(nums []int) int {
    if len(nums) == 1 {
        return nums[0]
    }

    dpMax := make([]int, len(nums), len(nums))
    dpMin := make([]int, len(nums), len(nums))

    dpMax[0] = nums[0]
    dpMin[0] = nums[0]

    for i := 1; i < len(nums); i++ {
        dpMax[i] = max(dpMin[i - 1] * nums[i], dpMax[i - 1] * nums[i], nums[i])
        dpMin[i] = min(dpMin[i - 1] * nums[i], dpMax[i - 1] * nums[i], nums[i])
    }

    return max(dpMax...)
}

func max(params ...int) int {
    maxNum := -9999999999999999;
    for _, e := range params {
        if e > maxNum {
            maxNum = e
        }
    }
    return maxNum
}

func min(params ...int) int {
    minNum := 99999999999999999;
    for _, e := range params {
        if e < minNum {
            minNum = e
        }
    }
    return minNum
}

My Notes - 我的笔记

No notes