Maximum Product Subarray

来源:互联网 发布:matalab y引入数据 编辑:程序博客网 时间:2024/05/01 12:01

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

Example

For example, given the array [2,3,-2,4], the contiguous subarray [2,3] has the largest product = 6.

这道题采用动规的思路做,当前的最大值有三种情况: 1. nums[i] 它自己本身,不包含其他的 2. max[i-1] * nums[i] 3. min[i-1]* nums[i]。 2 3 两种情况对应的是如果当前树是负数的话,那么跟前面的最小值相乘可能会得到最大值,以及当前是正数,跟前面的最大值相乘可能得到最大值。


空间上可以优化,但是目前这个做法好像跟数组保存没有太大区别。。:

代码:

public int maxProduct(int[] nums) {        // write your code here        if(nums == null || nums.length == 0) return 0;        if(nums.length == 1) return nums[0];        //int [] max = new int[nums.length];        //int[] min = new int[nums.length];        int max;        int min;        //max[0] = min[0] = nums[0];        max = min = nums[0];        int result = min;        for(int i = 1;i<nums.length;i++){            int preMax = max;            int preMin = min;            max = Math.max(nums[i], Math.max(preMin*nums[i], preMax*nums[i]));            min = Math.min(nums[i], Math.min(preMin*nums[i], preMax*nums[i]));            result = Math.max(result, max);        }        return result;    }


0 0
原创粉丝点击