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

    思路:DP。这里我们实际上不需要O(n)的空间,只需要用变量将遍历到的最大值记录下来就可以。

    其中,因为求的是数的乘积,有可能原本两个都是负的值相乘后会成为最大的乘积。

    因此,我们需要维护两个变量,MaxPre和MinPre。

    MaxPre为最后一位是当前位置前一位的区间最大乘积。

    MinPre为最后一位是当前位置前一位的区间最小乘积。

    之后,将当前位置考虑在内的话,有:

    MaxSoFar = max(max(MaxPre * nums[i], MinPre * nums[i]), nums[i]);

    MinSoFar = min(min(MinPre * nums[i], MaxPre * nums[i]), nums[i]);

    然后用MaxResFound记录下迭代过程中MaxSoFar的最大值,即为结果。

     1 class Solution {
     2 public:
     3     int maxProduct(vector<int>& nums) {
     4         int n = nums.size();
     5         if (n == 0) return 0;
     6         int MaxSoFar, MinSoFar, MaxResFound, MaxPre, MinPre;
     7         MaxPre = MinPre = MaxSoFar = MinSoFar = MaxResFound = nums[0];
     8         for (int i = 1; i < n; i++)
     9         {
    10             MaxSoFar = max(max(MaxPre * nums[i], MinPre * nums[i]), nums[i]);
    11             MinSoFar = min(min(MinPre * nums[i], MaxPre * nums[i]), nums[i]);
    12             MaxResFound = max(MaxResFound, MaxSoFar);
    13             MaxPre = MaxSoFar;
    14             MinPre = MinSoFar;
    15         }
    16         return MaxResFound;
    17     }
    18 };
  • 相关阅读:
    Git远程操作
    696. Count Binary Substrings
    693. Binary Number with Alternating Bits
    821. Shortest Distance to a Character
    345. Reverse Vowels of a String
    89. Gray Code
    数组操作符重载
    C++字符串反转
    马克思的两面性-来自网友
    C++字符串
  • 原文地址:https://www.cnblogs.com/fenshen371/p/4935078.html
Copyright © 2011-2022 走看看