您的位置:首页 > 其它

LeetCode:Maximum Product Subarray

2016-01-12 15:20 337 查看


Maximum Product Subarray

Total Accepted: 48973 Total
Submissions: 231867 Difficulty: Medium

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
.

Hide Tags
Array Dynamic
Programming

Hide Similar Problems
(M) Maximum Subarray (E)
House Robber (M) Product of Array Except Self

code:

class Solution {
public:
    int maxProduct(vector<int>& nums) {
        
        int n = nums.size();
        int front=1,back=1;
        int product = INT_MIN;
        
        for(int i=0;i<n;i++) {
            front *= nums[i];
            back *= nums[n-i-1];
            product = max(product, max(front,  back));
            front = front?front:1;
            back = back?back:1;
        }
        return product;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: