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


    思路:从左至右遍历数组,记录下以当前所遍历到的元素结尾的子数组积的最大值和最小值(由于数组里面可能存在负数),同一时候记录下得到的全部最大值中最大的。循环结束时。得到的全部最大值中最大的即为所求。


    代码:

    int Solution::maxProduct(int A[],int n)
    {
        if(n == 1)
            return A[0];
        int max_temp = A[0];
        int min_temp = A[0];
        int result = A[0];
        int i;
        for(i = 1;i < n;i++)
        {
            int max_temp2 = max_temp * A[i];
            int min_temp2 = min_temp * A[i];
            max_temp = max(max_temp2,max(min_temp2,A[i]));
            min_temp = min(min_temp2,min(max_temp2,A[i]));
            if(max_temp > result)
                result = max_temp;
        }
        return result;
    }
    


    版权声明:本文博主原创文章,博客,未经同意不得转载。

  • 相关阅读:
    15.Linux的文件结构
    14.管道模型
    13.ubuntu下Qt5无法使用中文的问题解决
    12.时钟与信号
    11.进程控制
    10.设备文件
    [GXOI/GZOI2019]旅行者
    [GXOI/GZOI2019]旧词
    [BJOI2019] 删数
    [BJOI2019] 光线
  • 原文地址:https://www.cnblogs.com/zfyouxi/p/4817634.html
Copyright © 2011-2022 走看看