列表

详情


NC24613. [USACO 2011 Jan S]Profits

描述

The cows have opened a new business, and Farmer John wants to see how well they are doing. The business has been running for N (1 <= N <= 100,000) days, and every day i the cows recorded their net profit P_i (-1,000 <= P_i <= 1,000).
Farmer John wants to find the largest total profit that the cows have made during any consecutive time period. (Note that a consecutive time period can range in length from one day through N days.) Help him by writing a program to calculate the largest sum of consecutive profits.

输入描述

* 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 

输出:

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)

上一题