zoukankan      html  css  js  c++  java
  • 最大连续和

    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.

    解法

    依次扫描。currsum保存上一个数结尾的最大和,maxsum保存全局最大和。那么碰到一个新的数x,有两种行为,一种是以它为头建立一个新的连续序列,一种是把它放在上一个数所在的序列的结尾,看哪个得到的和大一点就用哪个。

    注意初始化要比数据范围下界小。

    #include <algorithm>
    #include <iostream>
    
    using namespace std;
    
    int main(void) {
        int n;
        cin >> n;
        
        int currsum = -2000;
        int maxsum  = -2000;
        
        for (int i = 0; i < n; ++i) {
            int x;
            cin >> x;
            
            currsum = max(x, x+currsum);
            maxsum  = max(maxsum, currsum);
        }
        
        cout << maxsum;
    }
    
  • 相关阅读:
    Java时间转换的一个特性
    JS处理数据四舍五入
    DataReader分页性能测试
    Java通过cal.get(Calendar.MONTH)比真实月份少一个月
    sqlserver split函数
    一个CLR20r3 错误解决。
    Devexpress dll搜集
    正则表达式:小括号、中括号、大括号的区别
    Android手机有的不显示Toast
    保存页面数据的场所----Hidden、ViewState、ControlState
  • 原文地址:https://www.cnblogs.com/jt2001/p/6130399.html
Copyright © 2011-2022 走看看