152.Maximum Product Subarray

来源:互联网 发布:时时彩源码免费下载 编辑:程序博客网 时间:2024/04/30 21:14

题目

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.

解答

int maxProduct(vector<int>& nums) {    if (nums.size() == 0)        return 0;    int tmax = nums[0], tmin = nums[0], maxAns = nums[0];    for (int i = 1; i < nums.size(); i++) {        int mx = tmax, mn = tmin;        tmax = max(max(nums[i], mx * nums[i]), mn * nums[i]);        tmin = min(min(nums[i], mx * nums[i]), mn * nums[i]);        maxAns = max(tmax, maxAns);    }    return maxAns;}
0 0
原创粉丝点击