[DP解题] 乘积最大子序列
原题链接:https://leetcode.com/problems/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.
题目的意思是给定一个整形数组nums,要求在数组中找到连续的子序列使得子序列的乘积最大(子序列至少包含一个整数)
例如:给定数组 [2,3,-2,4],最大连续子序列乘积为6。因为最大的连续子序列 [2,3],其最大乘积为6。
[算法分析]
这道题最直接的方法就是用DP来做,而且要用两个dp变量,其中:
dpMax:代表nums数组中下标从[0...i]时的最大乘积
dpMin:代表nums数组中下标从[0...i]时的最小乘积
为什么呢?
初始时,当i=0时,即数组中的第一个元素:
dpMax=dpMin=answer=nums[0] (可能为0,正值,负值)
当i=1时:即数组中的第二个元素,这时要考虑几种情