LeetCode: Maximum Product Subarray

来源:互联网 发布:特殊字体生成器软件 编辑:程序博客网 时间:2024/06/06 17:40

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.

class Solution {public:    int maxProduct(int A[], int n) {        if(n == 0)            return 0;        int max = A[0], curMax = A[0], curMin = A[0];        for(int i = 1; i < n;i++)        {            int a = curMax*A[i];            int b = curMin*A[i];            curMax = std::max(std::max(a, b), A[i]);            curMin = std::min(std::min(a, b), A[i]);            max = std::max(max, curMax);        }        return max;    }};

Round 2:

class Solution {public:    int maxProduct(int A[], int n) {if(n == 0)return 0;int preMax[n] = {0};int max = A[0];int preMin = A[0];preMax[0] = A[0];for(int i = 1; i < n; i++){preMax[i] = std::max(A[i], std::max(A[i]*preMax[i-1], preMin * A[i]));preMin = std::min(A[i], std::min(A[i]*preMax[i-1], preMin * A[i]));if(preMax[i] > max)max = preMax[i];}return max;    }};


Round 3:

class Solution {public:    int maxProduct(vector<int>& nums) {int n = nums.size();if(n == 0)return 0;int min = nums[0], max = nums[0], result = nums[0];for(int i = 1; i < n; i++){    int op1 = nums[i] * max;    int op2 = nums[i] * min;max = std::max(nums[i], std::max(op1, op2));min = std::min(nums[i], std::min(op1, op2));result = std::max(max, result);}return result;    }};


0 0
原创粉丝点击