Leetcode--maximal continuous product sub-sequence

Source: Internet
Author: User


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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.