51Nod 1049 最大子段和

來源:互聯網
上載者:User



N個整數組成的序列a[1],a[2],a[3],…,a[n],求該序列如a[i]+a[i+1]+…+a[j]的連續子段和的最大值。當所給的整數均為負數時和為0。 例如:-2,11,-4,13,-5,-2,和最大的子段為:11,-4,13。和為20。 Input

第1行:整數序列的長度N(2 <= N <= 50000)第2 - N + 1行:N個整數(-10^9 <= A[i] <= 10^9)
Output
輸出最大子段和。
Input樣本
6-211-413-5-2
Output樣本

20

解題思路:

其實這個題很水的,我們只需要O(n)的演算法就能過,如果純暴力的話,應該是O(n^3),對於這個題來說我們只需要

一下和就行了,然後每次判斷這個和是不是>=0,如果是的話,那麼我們就加上a[i],否則sum=a[i],然後每次找最大值,最後輸出最大值就行了。

My Code:

#include <iostream>#include <cstdio>using namespace std;const int MAXN = 50000+5;int a[MAXN];int main(){    int n;    while(~scanf("%d",&n))    {        for(int i=1; i<=n; i++)            scanf("%d",&a[i]);        long long Max = -1, sum = 0;        for(int i=1; i<=n; i++)        {            if(sum >= 0)                sum += a[i];            else                sum = a[i];            if(sum > Max)                Max = sum;        }        printf("%lld\n",Max);    }    return 0;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.