Description
给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
Input
输入为2行,第一行为一个整数n,表示输入数组中整数的个数;第二行为数组中的各个整数,以空格分隔
注意,1<=n<=100000 ,且数组中任何一个整数的绝对值小于10000
Output
输出为一个整数,即最大和
比如输入为:
9
-2 1 -3 4 -1 2 1 -5 4
此时输出应为6,因为连续子数组 [4,-1,2,1] 的和最大,为 6
Sample Input 1
9 -2 1 -3 4 -1 2 1 -5 4
Sample Output 1
6
#include<bits/stdc++.h>
using namespace std;
int n,a;
vector<int> perm;
int main()
{
cin >> n;
int index = 0;
while(n--)
{
cin >> a;
perm.push_back(a);
}
//f[i] 表示以 nums[i] 结尾的最大子数组和。
int ans = perm[0],f = 0;
for(auto i : perm)
{
f = max(f,0) + i;//状态转移方程,以当前i下标的子最大值等于max()+当前的数
ans = max(ans,f);
}
cout << ans;
return 0;
}