Problem Description: For a given array, find the subsequence of the maximal value of the continuous product.
For example 0,-1,-3,-2, the maximum continuous product is 6 = (-3) * (-2)
Implementation ideas
This problem is similar to the maximum continuous and sub-sequence problem, and can be solved by finding a recursive formula and then using DP.
The key is to take into account the fact that the element may be negative in the process of finding the formula. Assuming that the elements are positive, the DP formula is:
Dp[i] = max (a[i],dp[i-1]*a[i]), multiply or not multiply, take the largest one
The element may be negative, so you can use Min and Max to separate the current maximum and minimum values, and if the current element is negative, the current minimum is the maximum value. In this way, the DP formula is:
max = max (max (max * a[i], min * a[i]), A[i]), find the maximum from Max * A[i] and min * a[i, compare with A[i]
min = min (min (max * A[i], min * a[i]), A[i]), ibid., just take the minimum value
The last Max is what you ask for.
public class Solution {public int maxproduct (int[] nums) { var len = nums. Length; if (len = = 0) { return 0; } var max = Nums[0];var min = Nums[0];var result = Nums[0]; for (var i = 1;i < Len; i++) { var Tmpmax = Math.max (Math.max (Max * nums[i], min * nums[i]), nums[i]); var tmpmin = M Ath. Min (math.min (max * nums[i], min * nums[i]), nums[i]); max = Tmpmax;min = Tmpmin;result = Math.max (result, max); } return result;} }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode--maximal continuous product sub-sequence