题目来源:洛谷
题目描述:
奶牛们开始了新的生意,它们的主人约翰想知道它们到底能做得多好。这笔生意已经做了N(1≤N≤100,000)天,每天奶牛们都会记录下这一天的利润Pi(-1,000≤Pi≤1,000)。
约翰想要找到奶牛们在连续的时间期间所获得的最大的总利润。(注:连续时间的周期长度范围从第一天到第N天)。
请你写一个计算最大利润的程序来帮助他。
输入格式:
-
Line 1: A single integer: N
-
Lines 2…N+1: Line i+1 contains a single integer: P_i
输出格式:
- Line 1: A single integer representing the value of the maximum sum of profits for any consecutive time period.
输入输出样例:
输入1
7
-3
4
9
-2
-5
8
-3
输出1
14
说明/提示:
The maximum sum is obtained by taking the sum from the second through the sixth number (4, 9, -2, -5, 8) => 14.
思路:
动态规划
设f[i]为第i天的最大总利润,则f[i]=max(f[i-1]+a[i],a[i])
初始化 f[1]=a[1]
AC代码:
#include<bits/stdc++.h>
using namespace std;
int n,a[100010],f[100010],anss=-9999999;
int main()
{
cin>>n;
for (int i=1;i<=n;i++) cin>>a[i];
f[1]=a[1];
for (int i=2;i<=n;i++)
{
f[i]=max(f[i-1]+a[i],a[i]);
anss=max(anss,f[i]);
}
cout<<anss<<endl;
return 0;
}