152. Maximum Product Subarray

来源:互联网 发布:云计算概念技术与架构 编辑:程序博客网 时间:2024/05/20 16:33

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.


public class Solution {    public int maxProduct(int[] nums) {        if(nums==null || nums.length==0)            return 0;        int global = nums[0];        int max_local = nums[0];        int min_local = nums[0];        for(int i=1;i<nums.length;i++)        {            int max_copy = max_local;            max_local = Math.max(Math.max(nums[i],max_local*nums[i]),min_local*nums[i]);            min_local = Math.min(Math.min(nums[i],max_copy*nums[i]),min_local*nums[i]);//维护一个最小值。负负得正            global = Math.max(max_local,global);        }        return global;    }}


原创粉丝点击