【编程练习】最大连续数列和

最大连续数列和

时间限制:C/C++ 3秒,其他语言 6秒
空间限制:C/C++ 32768K,其他语言 65536K
64bit IO Format: %lld
本题可使用本地IDE编码,不做跳出限制,编码后请点击“保存并调试”按钮进行代码提交。


题目描述

对于一个有正有负的整数数组,请找出总和最大的连续数列。
给定一个int数组A和数组大小n,请返回最大的连续数列的和。保证n的大小小于等于3000。

测试样例:

[1,2,3,-6,1]
返回:6


源码

测试通过

class MaxSum {
public:
    int getMaxSum(vector<int> A, int n) {
        // write code here
        int sum = 0;
        int max = -32767;
        for(size_t i=0;i<A.size();++i){
            sum+=A[i];
            if(sum>max)
                max=sum;
            if(sum<0)
                sum=0;
        }
        return max;
    }
};

猜你喜欢

转载自blog.csdn.net/sofia_m/article/details/81148647