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

**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;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,775评论 0 33
  • 夏天就要去了 逝水年华 如流动的心 错过了梅 在那冬季 纷落的花 丢弃在春梦里 远远的水塘 那莲花出水 此时我收拾...
    可依伴秋阅读 261评论 0 0
  • http://www.jianshu.com/p/7fc475180a51 swift 下使用svgKit htt...
    名字被谁占了阅读 380评论 0 0