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.

     [暴力解法]:

    时间分析:

    空间分析:

     [优化后]:

    时间分析:

    空间分析:

    [奇葩输出条件]:

     

    Your input
    [2,3,-2,4]
    Your answer
    24
    Expected answer
    6

     

    [奇葩corner case]:

    [思维问题]:

    [英文数据结构或算法,为什么不用别的数据结构或算法]:

    记忆化搜索的dp,划分型 kandane

    [一句话思路]:

    max = Math.max(max, max * nums[i]);是记忆化搜索,能保证全局最优解24;

     

    maxhere = Math.max(Math.max(maxherepre * A[i], minherepre * A[i]), A[i]);
    保证二者之间相对较大,只能保证负号之前的局部最优解6 
    maxherepre = maxhere;
    minhere用的是之前存好的maxherepre,不是改变后的maxhere。所以要提前存

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

      [五分钟肉眼debug的结果]:

    [总结]:

    minhere用的是之前存好的maxherepre,不是改变后的maxhere。所以要提前存。

    [复杂度]:Time complexity: O(n) Space complexity: O(1)

    [算法思想:迭代/递归/分治/贪心]:

    [关键模板化代码]:

    [其他解法]:

    [Follow Up]:

    [LC给出的题目变变变]:

     [代码风格] :

     [是否头一次写此类driver funcion的代码] :

     [潜台词] :

    Local optimal solution

    class Solution {
        public int maxProduct(int[] nums) {
            //cc
            if (nums == null || nums.length == 0) return 0;
            
            //ini: 5 variables
            int maxHere = nums[0];
            int minHere = nums[0];
            int maxHerePre = nums[0];
            int minHerePre = nums[0];
            int result = nums[0];
            
            //calculate
            for (int i = 1; i < nums.length; i++) {
                maxHere = Math.max(Math.max(maxHerePre * nums[i], minHerePre * nums[i]), nums[i]);
                minHere = Math.min(Math.min(maxHerePre * nums[i], minHerePre * nums[i]), nums[i]);
                maxHerePre = maxHere;
                minHerePre = minHere;
                result = Math.max(result, maxHere);
            }
            
            //return
            return result;
        }
    }
    View Code
  • 相关阅读:
    Linux下的vim简易配置与Windows下的vim配置
    ASP.NET MVC2(Visual Studio.NET 2010)学习之路(一)
    NonSQL
    完成公司核名
    调试iOS 已经发布代码 Crash 文件分析出出错对应代码
    iOS RSA公钥加密数据 服务端接受PHP私钥解密 反过服务端公钥加密数据 iOS端私钥解密数据
    iOS 日期格式串 setDateFormat 显示格式代码
    iOS5 UI 设计新手段 Storyboard
    UIEdgeInsets
    xcode调试找出错误行
  • 原文地址:https://www.cnblogs.com/immiao0319/p/9371580.html
Copyright © 2011-2022 走看看