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

    这道题需要用动态规划方法解决(自底向上),首先动态规划有两个特点,一个是最优子结构,另一个是重叠子问题。我们先求出子问题的最小乘积(可能会是负数)和最大乘积,然后与当前的数组值相乘和当前的值进行比较(maxhere和minhere),同样保存最大值和最小值。代码如下:

    public class Solution {

        public int maxProduct(int[] nums) {

            int maxherepre = nums[0];

            int minherepre = nums[0];

            int maxsofar = nums[0];

            int maxhere=nums[0],minhere=nums[0];

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

                maxhere = Math.max(nums[i],Math.max(maxherepre*nums[i],minherepre*nums[i]));

                minhere = Math.min(nums[i],Math.min(maxherepre*nums[i],minherepre*nums[i]));

                maxsofar = Math.max(maxsofar,maxhere);

                maxherepre = maxhere;

                minherepre = minhere;

            }

            return maxsofar;

        }

    }

  • 相关阅读:
    2015年终总结
    mmzb游戏事故分析
    为sproto手写了一个python parser
    Lua小技巧
    Techparty-广州 10 月 31 日 Docker 专场沙龙 后记
    1password密码库格式更新
    SSL加密与系统时间
    webpack的学习使用三
    webpack的学习使用二
    webpack的学习使用一
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6357424.html
Copyright © 2011-2022 走看看