1. 程式人生 > >#Leetcode# 152. Maximum Product Subarray

#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 強一丟丟!(一丟丟而已)