LintCode乘积最大子序列

找出一个序列中乘积最大的连续子序列(至少包含一个数)。

样例

比如, 序列 [2,3,-2,4] 中乘积最大的子序列为 [2,3] ,其乘积为6。

public class Solution {
    /**
     * @param nums: an array of integers
     * @return: an integer
     */
    public int maxProduct(int[] nums) {
        if(null == nums || nums.length <= 0)
        {
            return 0;
        }
        
        int max = nums[0];
        int min = nums[0];
        int mostMax = max;
        
        for(int i = 1;i < nums.length;i++)
        {
            int tempMax = max;
            max = Math.max(Math.max(nums[i], tempMax * nums[i]),min * nums[i]);
            min = Math.min(Math.min(nums[i], tempMax * nums[i]),min * nums[i]);

            if(max > mostMax)
            {
                mostMax = max;
            }
        }
        return mostMax;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容