【leetcode】152. Maximum Product Subarray

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ghscarecrow/article/details/86618795

Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.

Example 1:

Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.

Example 2:

Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.

解题思路:key1:子序列意味着要在原数组中连续的序列,倘若放弃当前元素,即意味着之前所有元素均要放弃。

                  key2:与负数相乘,最大变最小,最小变最大。

class Solution {
    public int maxProduct(int[] nums) {
        int max = nums[0];
        int imax = max;
        int imin = max;
        
        for(int i = 1;i < nums.length;i++) {
            if(nums[i] < 0) {
                //为负数,与最小数相乘变最大,与最大数相乘变最小。所以需要交换
                int temp = imax;
                imax = imin;
                imin = temp;
            }
            
            imax = Math.max(nums[i],imax * nums[i]);//因为要连续,所以如果不选择当前元素,则表明需要跟以前的所有元素割舍
            imin = Math.min(nums[i],imin * nums[i]);
            
            max = Math.max(imax,max);
        }
        
        return max;
    }
}

猜你喜欢

转载自blog.csdn.net/ghscarecrow/article/details/86618795