LeetCode 152. Maximum Product Subarray

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.

1、这道题要求连续子串乘积的最大值。

2、因为是连续子串,因此index = i处的最大值只与index = i – 1处的值有关。

3、因为是乘法运算,index = i – 1处只需记录最大值与最小值,其他值与index = i相乘会介于他们之间,不影响结果

Java代码如下所示:

public class Solution {
    public int maxProduct(int[] nums) {
        int[] max = new int[nums.length];
        int[] min = new int[nums.length];
        max[0] = min[0] = nums[0];
        int result = max[0];
        for(int i = 1; i < nums.length; i++) {
        	max[i] = Math.max(nums[i], Math.max(max[i - 1] * nums[i], min[i - 1] * nums[i]));
        	min[i] = Math.min(nums[i], Math.min(max[i - 1] * nums[i], min[i - 1] * nums[i]));
        	if(result < max[i]) {
        		result = max[i];
        	}
        }
        return result;
    }
    public static void main(String[] args) {
    	int[] nums = {2,3,-2,4};
    	Solution solution = new Solution();
    	System.out.println(solution.maxProduct(nums));
    }
}

点赞