题解 | #连续子数组最大和(ACM版本)#

连续子数组最大和(ACM版本)

http://www.nowcoder.com/practice/1718131e719746e9a56fb29c40cc8f95

很巧妙的解决方法,也不是什么动态规划,只要想明白了这种子数组的出现规律就很好明白。

32位int塞不下某些数据,需要用64位long。

#include <vector>
#include <climits>

using namespace std;

int main()
{
    int n;
    scanf("%ld", &n);
    vector<long> arr(n);
    for (int i = 0; i < n; i++)
    {
        scanf("%ld", &arr[i]);
    }
    
    long max = 0;
    long cur = 0;
    for (const long& value: arr)
    {
        cur = (cur + value > 0 ? cur + value : 0);
        max = (cur > max ? cur : max);
    }
    
    if (max == 0)
    {
        max = LONG_MIN;
        for (const long& value: arr)
        {
            max = (max > value ? max : value);
        }
    }
    
    printf("%ld", max);
}
全部评论

相关推荐

WhiteAlbum...:学院本2中大厂垂直实习➕acm比赛 秋招0面试
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务