美文网首页
[LeetCode 152] Maximum Product S

[LeetCode 152] Maximum Product S

作者: 灰睛眼蓝 | 来源:发表于2019-08-07 15:47 被阅读0次

    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.
    

    Solution & Code

    class Solution {
        // 用max sum subarray的思路, DP
        // 但是不能只求maxSubarray Array,因为乘法有正负,负负为正,所以不能只简单取 
        // preProductArray [i] = Math.max (preProductArray [i - 1] * nums[i], nums[i]);
        // max = Math.max (preProductArray [i], max); 
        // eg. [-2, 3, -4]。如果只上述算,那么结果就是3,因为到了3的时候,-6就被舍弃了。
        
        // 所以Idea是,keep max and min for current index, and keep it for the next iteration
        public int maxProduct(int[] nums) {
            if (nums == null || nums.length == 0)
                return 0;
            
            int maxProduct = nums[0];
            int minProduct = nums[0];
            int maxResult = nums[0];
            
            for (int i = 1; i < nums.length; i++) {
                int maxTemp = maxProduct;
                maxProduct = Math.max (Math.max (maxProduct * nums[i], nums[i]), minProduct * nums[i]);
                minProduct = Math.min (Math.min (minProduct * nums[i], nums[i]), maxTemp * nums[i]);
                
                maxResult = Math.max (maxResult, maxProduct);
            }
            
            return maxResult;
        }
    }
    

    相关文章

      网友评论

          本文标题:[LeetCode 152] Maximum Product S

          本文链接:https://www.haomeiwen.com/subject/inaodctx.html