友情支持

如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜

支付宝

微信

有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。

wx jikerizhi

公众号的微信号是: jikerizhi因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。

152. Maximum Product Subarray

这道题的阶梯思路跟另外某个题的解题思路很类似!

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.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
 * Runtime: 1 ms, faster than 97.91% of Java online submissions for Maximum Product Subarray.
 *
 * Memory Usage: 36.4 MB, less than 100.00% of Java online submissions for Maximum Product Subarray.
 *
 * Copy form: https://leetcode.com/problems/maximum-product-subarray/discuss/48230/Possibly-simplest-solution-with-O(n)-time-complexity[Possibly simplest solution with O(n) time complexity - LeetCode Discuss]
 */
public int maxProduct(int[] nums) {
    // store the result that is the max we have found so far
    int result = nums[0];
    // max/min stores the max/min product of
    // subarray that ends with the current number nums[i]
    for (int i = 1, max = result, min = result; i < nums.length; i++) {
        // multiplied by a negative makes big number smaller, small number bigger
        // so we redefine the extremums by swapping them
        if (nums[i] < 0) {
            int temp = max;
            max = min;
            min = temp;
        }
        // max/min product for the current number is either the current number itself
        // or the max/min by the previous number times the current one
        min = Math.min(nums[i], min * nums[i]);
        max = Math.max(nums[i], max * nums[i]);

        // the newly computed max value is a candidate for our global result
        result = Math.max(result, max);
    }
    return result;
}