152. Maximum Product Subarray

来源:互联网 发布:工程项目做账软件 编辑:程序博客网 时间:2024/06/06 20:30

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) {        if(nums.size() == 0)            return 0;        if(nums.size() == 1)            return nums[0];                long nodeMin = nums[0], nodeMax = nums[0];        long myMax = nodeMax;        for(int i = 1; i < nums.size(); i ++){            long temp1 = nodeMin * nums[i], temp2 = nodeMax * nums[i];            nodeMin = min(temp1, temp2);            nodeMin = min(nodeMin,(long) nums[i]);            nodeMax = max(temp1,temp2);            nodeMax = max(nodeMax,(long) nums[i]);            if(nodeMax > myMax)                myMax = nodeMax;        }        return myMax;    }};