NC24613. [USACO 2011 Jan S]Profits
描述
输入描述
* Line 1: A single integer: N
* Lines 2..N+1: Line i+1 contains a single integer:
输出描述
* 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
输出:
14
说明:
The maximum sum is obtained by taking the sum from the second through the sixth number (4, 9, -2, -5, 8) => 14.C++14(g++5.4) 解法, 执行用时: 31ms, 内存消耗: 1256K, 提交时间: 2020-03-07 14:53:01
#include<bits/stdc++.h> using namespace std; int a[200005],c[200005]; int main() { int n,ans=-1000; cin>>n; for(int i=1;i<=n;i++) { cin>>a[i]; c[i]=max(c[i-1]+a[i],a[i]); ans=max(ans,c[i]); } cout<<ans; return 0; }
C++11(clang++ 3.9) 解法, 执行用时: 39ms, 内存消耗: 864K, 提交时间: 2020-03-09 16:44:17
#include<bits/stdc++.h> using namespace std; int a[100010],n,m=-1e9;int main(){cin>>n;for(int i=1;i<=n;i++){cin>>a[i];a[i]=max(a[i-1]+a[i],a[i]);m=max(m,a[i]);}cout<<m<<endl;return 0;}
Python3 解法, 执行用时: 271ms, 内存消耗: 4568K, 提交时间: 2021-12-16 22:21:31
n=int(input()) ans=-1001 t=0 for i in range(n): a=int(input()) t+=a ans=max(ans,t) if t<0: t=0 print(ans)