152.[LeetCode] Maximum Product Subarray

Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.

Example 1:

Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.

Example 2:

Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.





class Solution {
public:
    int maxProduct(vector<int>& nums) {
        int ans=nums[0],frontprod=1,backprod=1;
        int n=nums.size();
        for(int i=0;i<n;i++){
            frontprod*=nums[i];
            backprod*=nums[n-i-1];
            ans=max(ans,max(frontprod,backprod));
            frontprod=frontprod == 0 ? 1:frontprod;
            backprod=backprod == 0 ? 1 : backprod;
 
        }
       return ans; 
    }
};

 

posted @ 2019-02-24 22:41  WhoDreamsSky  阅读(82)  评论(0编辑  收藏  举报