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;}