leetcode---Maximum Product Subarray

来源:互联网 发布:178个经典c语言源代码 编辑:程序博客网 时间:2024/06/06 01:14

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.

class Solution {public:    int maxProduct(vector<int>& nums)     {        int n = nums.size();        if(n == 1)            return nums[0];        int tmpMin = nums[0];        int tmpMax = nums[0];        int ans = nums[0];        for(int i=1; i<n; i++)        {            int tmp = tmpMax;            tmpMax = max( max(tmpMax * nums[i], nums[i]), nums[i] * tmpMin);            tmpMin = min( min(tmp * nums[i], nums[i]), nums[i] * tmpMin);            ans = max(ans, tmpMax);        }        return ans;    }};
0 0
原创粉丝点击