1. 线性DP 152. 乘积最大子数组

152. 乘积最大子数组  https://leetcode-cn.com/problems/maximum-product-subarray/

 

func maxProduct(nums []int) int {
	preMax,preMin,curMax,curMin,res := nums[0],nums[0],1,1,nums[0]
	for i:=1;i<len(nums);i++{
		if nums[i] > 0{
			curMax = MAX(preMax,1)*nums[i]
			curMin = MIN(preMin,1)*nums[i]
		}else{
			curMax = MIN(preMin,1)*nums[i]
			curMin = MAX(preMax,1)*nums[i]
		}
		preMax = curMax
		preMin = curMin
		if curMax > res{
			res = curMax
		}
	}
	return res
}

func MAX(i,j int) int{
	if i<j{
		return j
	}else{
		return i
	}
}

func MIN(i,j int) int{
	if i<j{
		return i
	}else{
		return j
	}
} 

  

 

posted on 2020-04-20 16:50  wsw_seu  阅读(138)  评论(0编辑  收藏  举报

导航