2015年6月16日星期二

Maximum Product Subarray leetcode

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.
与maximum subarray不同, 这道题不仅要维护一个max 还要维护一个min
时间复杂度为O(n). 

public class Solution {
    public int maxProduct(int[] nums) {
        if (nums.length == 0) {
            return 0;
        }
        int len = nums.length;
        int[] max = new int[len];
        int[] min = new int[len];
        max[0] = min[0] = nums[0];
        int res = max[0];
        for (int i = 1; i < len; i++) {
        
            max[i] = Math.max(Math.max(nums[i], max[i-1] * nums[i]), min[i-1] * nums[i]);
            min[i] = Math.min(Math.min(nums[i], min[i-1] * nums[i]), max[i-1] * nums[i]);
            res = Math.max(res, max[i]);
 
        }
        return res;
    }
}
public class Solution {
    public int maxProduct(int[] nums) {
        int max = nums[0];
        int min = nums[0];
        int res = nums[0];
        for (int i = 1; i < nums.length; i++) {
            int a = nums[i] * max;//a,b需要提前算出 因为算min时候max值会变化
            int b = nums[i] * min;
            max = Math.max(nums[i], Math.max(a, b));
            min = Math.min(nums[i], Math.min(a, b));
            res = Math.max(max, res);
        }
        return res;
    }
}

没有评论:

发表评论