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

    题意:

      题目中给出一个(至少包含一个元素)整形数组,求一个子数组(元素连续),使得其元素之积最大。

      最直接了当的方法,当然是暴力穷举,但是其O(n^2)是无法通过LeetCode的OJ的。

      以下给出了本题的解决方法,O(n)时间复杂度,C++实现。

     1 class Solution {
     2 public:
     3     int maxProduct(int A[], int n) {
     4             int nMaxPro = A[0];
     5             int max_tmp = A[0];
     6             int min_tmp = A[0];
     7 
     8             for(int i = 1; i< n; ++i){
     9                 int a = A[i] * max_tmp;
    10                 int b = A[i] * min_tmp;
    11 
    12                 max_tmp = (( a > b ? a : b ) > A[i]) ? ( a > b ? a : b ) : A[i];
    13                 min_tmp = (( a < b ? a : b ) < A[i]) ? ( a < b ? a : b ) : A[i];
    14 
    15                 nMaxPro = (nMaxPro > max_tmp) ? nMaxPro : max_tmp;
    16             }
    17 
    18             return nMaxPro;
    19     }
    20 };

    运行结果:

     

    希望各位看官不吝赐教,小弟感谢~!

  • 相关阅读:
    Angel investor
    [HNOI 2003]消防局的设立
    [USACO 08JAN]Telephone Lines
    [Luogu 2265]路边的水沟
    [NOI 2010]航空管制
    [HNOI 2004]敲砖块
    [Luogu 1730]最小密度路径
    [USACO 13NOV]No Change
    [POJ 1006]生理周期
    [AHOI 2012]树屋阶梯
  • 原文地址:https://www.cnblogs.com/jiabei521/p/4025773.html
Copyright © 2011-2022 走看看