#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;
    }
};

  FH 今天感冒了呀 没想到这个 $n^2$ 也能过 本来自己写写的乱七八糟 还是 FH 强一丢丢!(一丢丢而已)

猜你喜欢

转载自www.cnblogs.com/zlrrrr/p/10055634.html