Maximum Product Subarray——LeetCode

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.

题目大意:给定一个数组,找出最大连续子数组乘积。

解题思路:

解法一、我是用动态规划来解,因为都是整数,还是比较简单,从前往后遍历一次,需要维护比较三个变量,当前最小值,当前最大值,全局最大值。为什么需要当前最小值呢?不是求最大乘积嘛,因为如果当前数是负的,并且当前最小值也是负的,那么乘积可能就是下一个最大值。

LeetCode官方题解递推公式:

Let us denote that:



f(k) = Largest product subarray, from index 0 up to k.

Similarly,



g(k) = Smallest product subarray, from index 0 up to k.

Then,



f(k) = max( f(k-1) * A[k], A[k], g(k-1) * A[k] )

g(k) = min( g(k-1) * A[k], A[k], f(k-1) * A[k] )
    public int maxProduct(int[] nums) {

        if (nums == null || nums.length == 0) {

            return 0;

        }

        int res = nums[0], min = nums[0], max = nums[0];

        for (int i = 1; i < nums.length; i++) {

            int curr_min = min * nums[i];

            int curr_max = max * nums[i];

            min = min(curr_min, curr_max, nums[i]);

            max = max(curr_min, curr_max, nums[i]);

            res = max(res, min, max);

        }

        return res;

    }



    int min(int a, int b, int c) {

        int tmp = Math.min(a, b);

        return Math.min(tmp, c);

    }



    int max(int a, int b, int c) {

        int tmp = Math.max(a, b);

        return Math.max(tmp, c);

    }

解法二,上面说了,数组里都是整数。

①假设没有0,那么相乘的绝对值都是一直扩大的。所以可以这样考虑,偶数个负数,那么最大乘积就是所有的乘起来;要处理的就是奇数个负数的情况,这时就考虑舍弃左边第一个负数以左的乘积,或舍弃右边第一个负数以右的乘积。

②我们这里是有0的,我们可以考虑0将给定的数组划分为几个子数组,然后用①中的方式比较这些子数组中最大的乘积。

Talk is cheap>>

    public int maxProduct2(int[] nums) {

        if (nums == null || nums.length == 0) {

            return 0;

        }

        int max = Integer.MIN_VALUE;

        int prod = 1;

        for (int i = 0; i < nums.length; i++) {

            prod *= nums[i];

            max = Math.max(max, prod);

            if (nums[i] == 0) {

                prod = 1;

            }

        }

        prod = 1;

        for (int i = nums.length - 1; i >= 0; i--) {

            prod *= nums[i];

            max = Math.max(max, prod);

            if (nums[i] == 0) {

                prod = 1;

            }

        }

        return max;

    }

 

你可能感兴趣的:(LeetCode)