凌云的博客

成功=工作+游戏+少说空话

LeetCode 算法题 53. Maximum Subarray

分类:algorithm| 发布时间:2016-10-20 14:06:00


题目

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) {
        const int n = nums.size();
        int ans=nums[0], sum = 0;
        for (int i = 0; i < n; i++) {
            sum += nums[i];
            ans = max(sum, ans);
            sum = max(sum, 0);
        }

        return ans;
    }
};