Leetcode 152 Maximum Product Subarray

来源:互联网 发布:mac aecc2017切换中文 编辑:程序博客网 时间:2024/06/06 18:13

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.

同样使dp的问题,但是值得注意的是,负数和负数相乘有可能是是个大的结果

于是min和max都要存下来

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






原创粉丝点击