【 USACO11JAN】 利潤 【洛谷P3009】

P3009 [USACO11JAN]利潤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.

牛們開了家新公司,這家公司已經運作了N天,財務報表顯示第i天獲得的利潤爲Pi , 有些天的利潤可能是個負數。約翰想給奶牛公司寫個新聞報道,以吹噓她們的業績。於是他 想知道,這家公司在哪一段連續的日子裏,利潤總和是最大的。

輸入輸出格式

輸入格式:
  • 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.


這道題很裸,但是思想和方法非常重要,儘管比較簡單。

不給詳細解釋,請大家仔細研讀代碼,如有不明,私信或評論或Q我(568251782)均可


#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>

const int MAXN  = 100000 + 10;
const int INF = 99999999;

int n,ans;
int num[MAXN];


int main()
{
	scanf("%d", &n);
	ans = -1*INF;
	for(int i= 1;i <= n;i++)
	{
		scanf("%d", &num[i]);
		if(num[i-1] > 0)
		{
			num[i] += num[i-1];
		}
		ans = std::max(ans, num[i]);
	}
	printf("%d", ans);
	return 0;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章