码迷,mamicode.com
首页 > 其他好文 > 详细

Maximum Product Subarray

时间:2019-12-21 22:54:06      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:return   least   line   复杂   wrap   ret   solution   min   nta   

Description

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

The product of the largest subsequence of the product, less than 2147483647

Example

Example 1:

Input:[2,3,-2,4]
Output:6

Example 2:

Input:[-1,2,4,1]
Output:8
思路:动态规划
public class Solution {
    /**
     * @param nums: An array of integers
     * @return: An integer
     */
    public int maxProduct(int[] nums) {
        int[] max = new int[nums.length];
        int[] min = new int[nums.length];
        
        min[0] = max[0] = nums[0];
        int result = nums[0];
        for (int i = 1; i < nums.length; i++) {
            min[i] = max[i] = nums[i];
            if (nums[i] > 0) {
                max[i] = Math.max(max[i], max[i - 1] * nums[i]);
                min[i] = Math.min(min[i], min[i - 1] * nums[i]);
            } else if (nums[i] < 0) {
                max[i] = Math.max(max[i], min[i - 1] * nums[i]);
                min[i] = Math.min(min[i], max[i - 1] * nums[i]);
            }
            
            result = Math.max(result, max[i]);
        }
        
        return result;
    }
}

  O(1)空间复杂度

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

  

Maximum Product Subarray

标签:return   least   line   复杂   wrap   ret   solution   min   nta   

原文地址:https://www.cnblogs.com/FLAGyuri/p/12078254.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!