寻找数组中的连续子序列的最大值

2017-03-28  本文已影响0人  juexin

**Maximum Subarray **(最基本的)
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int maxSum = nums[0];
        int cur = nums[0];
        for(int i=1;i<nums.size();i++)
        {
            cur = max(cur+nums[i],nums[i]);
            maxSum = max(maxSum,cur);
        }
        return maxSum;
    }
};

**Maximum Product Subarray **(乘积,分正负)
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(vector<int>& nums) {
        int minP = nums[0];
        int maxP = nums[0];
        int a = nums[0];
        int b = nums[0];
        int maxProduct = nums[0];
        for(int i=1;i<nums.size();i++)
        {
            a = nums[i]*minP;
            b = nums[i]*maxP;
            minP = min(min(a,b),nums[i]);
            maxP = max(max(a,b),nums[i]);
            maxProduct = max(maxProduct,maxP);
        }
        return maxProduct;
    }
};
上一篇 下一篇

猜你喜欢

热点阅读