[LeetCode]152. Maximum Product Subarray

https://leetcode.com/problems/maximum-product-subarray/

求子数组乘积最大值


记录以当前位置i为结尾的子数组乘积的最大值和最小值,以i + 1为结尾的子数组乘积的最大值一定是三选一:nums[i + 1];max * nums[i + 1];min * nums[i + 1]。中间不停update res,最终返回res即可

public class Solution {
    public int maxProduct(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int maxPre = nums[0];
        int minPre = nums[0];
        int res = maxPre;
        for (int i = 1; i < nums.length; i++) {
            int max = Math.max(nums[i], Math.max(maxPre * nums[i], minPre * nums[i]));
            int min = Math.min(nums[i], Math.min(maxPre * nums[i], minPre * nums[i]));
            res = Math.max(res, max);
            maxPre = max;
            minPre = min;
        }
        return res;
    }
}


你可能感兴趣的:(LeetCode)