Poj2593 Max sequence (calculate the sum of the two biggest non-Intersecting fields)

Source: Internet
Author: User

Mathematical poj Traversal

Reprint please indicate the source: http://blog.csdn.net/u012860063? Viewmode = Contents

Question link: http://poj.org/problem? Id = 2593

Description

Give you n integers A1, A2... an (| ai |<= 1000, 1 <= I <= N ).

You shoshould output S.

Input

The input will consist of several test cases. for each test case, one integer N (2 <= n <= 100000) is given in the first line. second line contains N integers. the input is terminated by a single line with n = 0.

Output

For each test of the input, print a line containing S.

Sample Input

5-5 9 -5 11 200

Sample output

40

Thought: For data a [], the largest child segment ending with a [I] and B [I] are solved from left to right, and then traversed from right to left, evaluate the maximum child segment and sum of the right side of a [I] (including a [I]), and output the maximum value of sum + B [I-1.

The Code is as follows:

#include <iostream>using namespace std;#define INF 0x3fffffff#define M 100000+17int a[M],b[M];int main(){int n,i;while(cin >> n && n){int sum = 0, MAX = -INF;for(i = 1; i <= n; i++){cin >> a[i];sum+=a[i];if(sum > MAX){MAX = sum;}b[i] = MAX;if(sum < 0){sum = 0;}}MAX = -INF;sum = 0;int ans = MAX, t;for(i = n; i > 1; i--){sum+=a[i];if(sum > MAX){MAX = sum;}t = MAX + b[i-1];if(t > ans){ans = t;}if(sum < 0){sum = 0;}}cout<<ans<<endl;}return 0;}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.