zoukankan      html  css  js  c++  java
  • 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.

    Overall, we need to loop through the array, at each new element, there're 2 options:
    u can either multiply the new element to the existing product,
    or start a new product from current index (discard previous results)

    in this process we need to maintain and update 2 values:
    max: the maximum cumulative product UP TO current element starting from SOMEWHERE in the past
    min: the minimum cumuliative product UP TO current element
    (because when we see a negative number, the "candidate" for max should instead become the previous min product, because a bigger number multiplied by negative becomes smaller)

    base case: max = min = res = nums[0], need max and min because max * (negative number) -> min
    induction rule:
    (1) multiply current element
    -> max1 = max * nums[i], max2 = min * nums[i], min1 = min * nums[i], min2 = max * nums[i]
    (2) not multiply current element
    -> max3 = nums[i], min3 = nums[i]
    max = max(max1, max2, max3), min = min(min1, min2, min3), res = max(res, max)

    M1: time: O(n), space: O(1)

    class Solution {
        public int maxProduct(int[] nums) {
            if(nums == null || nums.length == 0) {
                return 0;
            }
            int max = nums[0];
            int min = nums[0];
            int res = nums[0];
            for(int i = 1; i < nums.length; i++) {
                int tmp = max;
                max = Math.max(Math.max(max * nums[i], min * nums[i]), nums[i]);
                min = Math.min(Math.min(tmp * nums[i], min * nums[i]), nums[i]);
                res = Math.max(res, max);
            }
            return res;
        }
    }
  • 相关阅读:
    HTTP长连接、短连接使用及测试
    递归分治算法之二维数组二分查找(Java版本)
    Java二维数组的概念和使用方法
    java二维数组遍历
    HashMap多线程并发问题分析
    Linux 移动或重命名文件/目录-mv 的10个实用例子
    CSS fixed 定位元素失效的问题
    关于 JavaScript 中的继承
    React 虚拟 DOM 的差异检测机制
    下拉框中选项的快速定位
  • 原文地址:https://www.cnblogs.com/fatttcat/p/13662431.html
Copyright © 2011-2022 走看看