美文网首页
Array:求子数组最大乘积

Array:求子数组最大乘积

作者: 敲一手烂代码 | 来源:发表于2016-06-23 21:30 被阅读12次

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

public int maxProduct(int[] nums) {
        if (nums == null || nums.length ==0) {
            return -1;
        }
        int max = nums[0],min = nums[0],result = nums[0];
        for (int i = 1; i < nums.length; i++) {
            int temp = max;
            max = Math.max(Math.max(max*nums[i], min*nums[i]), nums[i]);
            min = Math.min(Math.min(temp*nums[i], min*nums[i]), nums[i]);
            result = Math.max(max, result);
        }
        return result;
    }

相关文章

网友评论

      本文标题:Array:求子数组最大乘积

      本文链接:https://www.haomeiwen.com/subject/aukodttx.html