zoukankan      html  css  js  c++  java
  • Maximum Product Subarray

    Maximum Product Subarray

    问题:

    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.

    思路:

      动态规划

      整体的最优解等于遍历所有的局部最优解中的最优解

      动态规划方程:

      max_local[i + 1] = Max(Max(max_local[i] * A[i], A[i]),  min_local * A[i])

      min_local[i + 1] = Min(Min(max_copy[i] * A[i], A[i]),  min_local * A[i])

    我的代码:

    public class Solution {
        public int maxProduct(int[] A) {
            if(A == null || A.length == 0) return 0;
            int n = A.length;
            int max = A[0];
            int[] maxLocal = new int[n];
            int[] minLocal = new int[n];
            maxLocal[0] = A[0];
            minLocal[0] = A[0];
            for(int i = 1; i < n; i++)
            {
                int localMax = maxLocal[i-1];
                maxLocal[i] = Math.max(Math.max(A[i],maxLocal[i-1]*A[i]),A[i]*minLocal[i-1]);
                minLocal[i] = Math.min(Math.min(A[i],minLocal[i-1]*A[i]),A[i]*localMax);
                max = Math.max(max,maxLocal[i]);
            }
            return max;
        }
    }
    View Code
    • 求解数组总整体的最优解最重要的思想就是整体的最优解等于遍历所有的局部最优解中的最优解
    • 该问题让我联想到了之前做的Maximum Subarray问题,之前一直是用的数学推导的方法,现在也替换成动态规划的方法,代码如下:
    public class Solution {
        public int maxSubArray(int[] A) {
            if(A == null || A.length == 0) return 0;
            int n = A.length;
            int[] localMax = new int[n];
            localMax[0] = A[0];
            int max = A[0];
            for(int i = 1; i < n; i++)
            {
                localMax[i] = Math.max(localMax[i-1]+A[i],A[i]);
                max = Math.max(max,localMax[i]);
            }
            return max;
        }
    }
    View Code
    • 局部最优解和前面的局部最优解有关系,要不要加上前面的?加上之后的效果是什么样子的?这是需要在循环里面更新的内容。
  • 相关阅读:
    Object.Instantiate 实例
    .idata数据的解析
    数据结构-静态链表
    数据结构-循环链表
    Android---两个视图间的淡入淡出
    HDU 4597 Play Game 2013 ACM-ICPC吉林通化全国邀请赛H题
    Android 编译时出现r cannot be resolved to a variable
    找工作笔试面试那些事儿(5)---构造函数、析构函数和赋值函数
    SFINAE 模板替换失败而非报错的应用
    模板实参推导 & xx_cast的实现
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4355203.html
Copyright © 2011-2022 走看看