您的位置:首页 > 其它

给定整数序列求连续子串最大和 - 滴滴出行2018校园招聘内推笔试-研发工程师

2017-08-26 19:00 615 查看
时间限制: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
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息