- 题目描述
给你一个整数数组 nums ,请你找出数组中乘积最大的连续子数组(该子数组中至少包含一个数字),并返回该子数组所对应的乘积。
示例 1:
输入: [2,3,-2,4]
输出: 6
解释: 子数组 [2,3] 有最大乘积 6。
示例 2:
输入: [-2,0,-1]
输出: 0
解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-product-subarray
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
-
思路
1、动态规划,需要注意的是不能只关注每一步的最大值,因为乘法中负负得正,所以也要关注每一步的最小值
2、搞清楚每一步的最大值最小值的计算就行了 -
代码
package main
import "fmt"
func main() {
test := []int{-2,-3,-2,4}
res := maxProduct(test)
fmt.Println(res)
}
func maxProduct(nums []int) int {
//max,min分别保存局部最大值,最小值,res为可返回的最值
max, min, res := nums[0],nums[0],nums[0]
for i:=1; i<len(nums); i++ {
tMax := max
max = compare(tMax*nums[i],min*nums[i],nums[i],"max")
min = compare(min*nums[i],tMax*nums[i],nums[i],"min")
if max > res {
res = max
}
}
return res
}
//根据op返回3个数的最大值或最小值
func compare(a int,b int,c int, op string) int {
if op == "max" {
if a > b {
if a > c {
return a
}
return c
}else{
if b > c {
return b
}
return c
}
}else{
//最小值
if a > b {
if b < c {
return b
}
return c
}else{
if a < c {
return a
}
return c
}
}
}