LeetCode - 152. Maximum Product Subarray - 思路详解 - C++

来源:互联网 发布:linux mysqldump 编辑:程序博客网 时间:2024/06/08 10:02

题目

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.

翻译

找出在给定的数组中连续子数组成绩最大。
比如,给定的数组为【2,3,-2,4】
连续子数组,成绩最大为6;

思路

我们会注意到,数组中数据可正可负。所以,有些棘手。

但是仔细分析。正数乘以正数为正数,负数乘以负数为正数。比如当前元素值为正数,则正数才会更大。即出现更大的值,如果出现负数,则乘以负数才会得到更大的值。
所以我们需要记录两个值,一个是最大值,一个是最小值。初始情况,最大值,最小值均为第一个元素。然后向后遍历数组,分别和最大值和最小值相乘得到结果,然后最大值和两者乘积结果中的最大值对比更新。
然后最小值和乘积结果中的最小值对比更新。

代码

class Solution {public:     int maxProduct(vector<int>& nums) {        int maxPro= nums[0];        int minPro = nums[0];        int res = nums[0];        int n = nums.size();        for(int i = 1 ;i < n; i++){            int t1 = maxPro*nums[i];            int t2 = minPro*nums[i];            //找到最大和最小            maxPro = max(max(t1,t2),nums[i]);            minPro = min(min(t1,t2),nums[i]);            res = max(maxPro,res);        }        return res;    }};
0 0