Premiumlab  

https://leetcode.com/problems/maximum-product-subarray/description/

 

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.

 

 

Sol:

 

class Solution {
    public int maxProduct(int[] nums) {
        
        // DP
        // Time O(n), Space O(1)
        
        int maxLocal = nums[0];
        int minLocal = nums[0];
        int global = nums[0];
        
        for (int i =1; i < nums.length; i++){
            int temp = maxLocal;
            maxLocal = Math.max(Math.max(nums[i] * maxLocal, nums[i] * minLocal), nums[i]);
            minLocal = Math.min(Math.min(nums[i] * temp, nums[i] * minLocal), nums[i]);
            global = Math.max(global, maxLocal);
        }
        
        return global;
        
    }
}

 

 
posted on 2017-08-18 16:03  Premiumlab  阅读(119)  评论(0编辑  收藏  举报