[leetcode]Maximum Product Subarray

来源:互联网 发布:图表数据区域格式 编辑:程序博客网 时间:2024/06/06 00:45

Maximum Product Subarray

 

Find the contiguous subarray within an array (containing at least one number) which has the largest product.

For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.

题目表述:找出乘积最大的连续子数组。

解题思路:该题类似最大连续子数组求和。 但这里的决策条件每次要保存两个状态即包括当前元素的最大乘积,与包括当前元素的最小乘积,

最大乘积主要用来维护运算过程中的正数连续包含其中的偶数个负数, 最小乘积主要用来维护连续中负数个数为奇的情况。

public class Solution {    public int maxProduct(int[] nums) {        if(nums == null || nums.length < 1) return 0;        int curMaxProduct = nums[0];        int curMinProduct = nums[0];        int maxProduct = nums[0];                for(int i = 1; i < nums.length; i++){            int tMax = nums[i] * curMaxProduct;            int tMin = nums[i] * curMinProduct;            int m = tMax;            int n = tMin;            if(tMax < tMin){                m = tMin;                n = tMax;            }            curMaxProduct = Math.max(nums[i], m);            curMinProduct = Math.min(nums[i], n);                        maxProduct = Math.max(maxProduct, curMaxProduct);        }                return maxProduct;    }}


0 0
原创粉丝点击