给定整数序列求连续子串最大和

来源:互联网 发布:当今社会热门网络话题 编辑:程序博客网 时间:2024/05/17 23:15

时间限制:1S
空间限制:32768K

题目描述:
给定无序整数序列,求连续子串最大和,例如{-23 17 -7 11 -2 1 -34},字串为{17 -7 11},最大和为21

输入描述:
输入为整数序列,数字用空格分割,如:-23 17 -7 11 -2 1 -34

输出描述:
输出子序列的最大和:21

示例:
输入
-23 17 -7 11 -2 1 -34

输出
21

思路:动规思想,更新遍历到当前位置的最大值,并且每次都判断一下是否大于答案,注意全为负数和一个数这些特殊情况。
如:-2 -1 -3 则输出-1

#include <iostream>using namespace std;int max(const int& a, const int& b){    return a>b?a:b;}int main(){    int a[10005];    int count = 0;    while(cin >> a[count++]);    count--;    int ans = 0;    int result = a[0];    for(int i = 0; i < count; ++i)    {        ans = max(ans+a[i], a[i]);        result = max(result, ans);    }    cout << result << endl;    return 0;}/*-23 17 -7 11 -2 1 -34*/
原创粉丝点击