首页 > 其他 > 详细

LeetCode #53 Maximum Subarray

时间:2018-01-25 23:56:26      阅读:351      评论:0      收藏:0      [点我收藏+]

Description


 

  Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

 

Input


  

[-2,1,-3,4,-1,2,1,-5,4]

 

 

Output


  

6 //the contiguous subarray [4,-1,2,1] has the largest sum = 6.

 

思路


  

  CLRS 第四章练习题 4.1-5,动态规划 5 mins 过,时间复杂度 O(n) 。

  

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

 

  

LeetCode #53 Maximum Subarray

原文:https://www.cnblogs.com/Bw98blogs/p/8353621.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!