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.

    Note that, we need to consider two cases:
    (1) negative numbers
              Store the minimum product to handle the case that new element < 0. Because if current element < 0, the product of two negative numbers (new element, and minimum product before the new element) become positive.
    (2) zeros
            When meets zero, current max and min product become 0, new search is needed from the next element.

    Therefore,  we can write down to function to store both + and - products:

    max_product = max{A[i]*min_product (when A[i]<0),  A[i]*max_product (when A[i]>0),  A[i] (when 0 occurs before A[i]) }.

    min_product = min{A[i]*min_product,  A[i]*max_product,  A[i] }.

     
    Because current sequence might start from any element, to get the final result, we also need to store the max product after each iteration "res = max(res, maxp);".
     
     1 class Solution {
     2 public:
     3     int maxProduct(vector<int>& nums) {
     4         int currentMin = nums[0];
     5         int currentMax = nums[0];
     6         int result = nums[0];
     7         
     8         for(int i = 1; i < nums.size(); i++){
     9             int tempMax = currentMax;
    10             int tempMin = currentMin;
    11             currentMax = max(nums[i], max(tempMin * nums[i], tempMax * nums[i]));
    12             currentMin = min(nums[i], min(tempMin * nums[i], tempMax * nums[i]));
    13             
    14             result = max(result, currentMax);
    15         }
    16         return result;
    17     }
    18 };
  • 相关阅读:
    【SpringCloud构建微服务系列】分布式链路跟踪Spring Cloud Sleuth
    【算法】LRU算法
    细说分布式锁
    【Python】Python3.4+Matplotlib详细安装教程
    LoRaWAN协议(二)--LoRaWAN MAC数据包格式
    LoRaWAN移植笔记(一)__RTC闹钟链表的实现
    cJSON_json包的C语言解析库
    LoRaWAN协议(一)--架构解析
    STM32L051 PVD的调试
    以帧为存储单位的循环stack
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4851720.html
Copyright © 2011-2022 走看看