#Leetcode# 152. Maximum Product Subarray

https://leetcode.com/problems/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 n = nums.size();
        int ans = INT_MIN;
        for(int i = 0; i < n; i ++) {
             int x = 1;
            for(int j = i; j < n; j ++) {
                x *= nums[j];
                ans = max(ans, x);
            }
        }
        return ans;
    }
};

 

posted @ 2018-12-02 21:59  丧心病狂工科女  阅读(118)  评论(0编辑  收藏  举报