• 152. Maximum Product Subarray


    Problem statement:

    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.

    Solution:

    It is similar with 53. Maximum Subarray. We should keep one more minimum product since the product of two negative number is a position number. The current max and min value should choose from three candidates, nums[i], cur_max * nums[i] and cur_min * nums[i].

    Time complexity is O(n).

    class Solution {
    public:
        int maxProduct(vector<int>& nums) {
            if(nums.empty()){
                return 0;
            }
            int cur_max = 0;
            int cur_min = 0;
            int pre_max = nums[0];
            int pre_min = nums[0];
            int tot_max = nums[0];
            for(int i = 1; i < nums.size(); i++){
                cur_max = max(nums[i], max(pre_max * nums[i], pre_min * nums[i]));
                cur_min = min(nums[i], min(pre_max * nums[i], pre_min * nums[i]));
                pre_max = cur_max;
                pre_min = cur_min;
                tot_max = max(tot_max, cur_max);
            }
            return tot_max;
        }
    };
  • 相关阅读:
    TinyOS功率编程指南
    深度学习入门资料
    通信常识
    CTF入门
    前端开发工具之服务器选择
    Spring
    NoSQL -- MongoDB
    NoSQL -- Redis
    mysql alter table修改表结构添加多个字段的几个写法
    gongle 访问助手安装
  • 原文地址:https://www.cnblogs.com/wdw828/p/6876426.html
Copyright © 2020-2023  润新知