[Two-segment continuous non-duplicate sequence and maximum] dynamic planning

Source: Internet
Author: User

Maximum subsequence

Timelimit: 1 second memorylimit: 32 megabyte

Totalsubmit: 156 accepted: 42

Description

Given a sequence composed of N integers, integers are positive and negative, and two consecutive subsequences that do not overlap are found so that the integers and the largest of them are obtained. Both sub-sequences can be empty.

Input

Multiple Input groups. The first action N in each group indicates the length of the sequence. The second action n integers indicates the input sequence.
0 <n <= 1,000,000

Output

For each input group, only one integer is returned, indicating the maximum sum.

Sample Input

9
185-580-889 701 964-878 353-761 608

Sample output

2273

Hint

For example, the input sequence is (701 964) and (608), and the Integer Range is)

 

 

#include <iostream>#include <cstdio>using namespace std;const int INF=1000005;int s[INF],lt[INF],rt[INF],dp[INF];int main(){    //freopen("in.txt","r",stdin);    int i,n;    while(cin >> n)    {        for (i=1;i<=n;i++)scanf("%d",&s[i]);        dp[n+1]=dp[0]=-INF;        lt[0]=rt[n+1]=-INF;        for (i=1;i<=n;i++)//正向        {            dp[i] = max(dp[i-1]+s[i],s[i]);        }         for (i=1;i<=n;i++)         {             lt[i] = max(dp[i],lt[i-1]);//             lt[i] = dp[i];         }        for (i=n;i>=1;i--)  //逆向        {            dp[i] = max(dp[i+1]+s[i],s[i]);        }         for (i=n;i>=1;i--)         {             rt[i] = max(dp[i],rt[i+1]);//                rt[i] = dp[i];         }         int sum=-INF;//枚举        for (i=1;i<=n;i++)        {            sum = max(sum,lt[i]+rt[i+1]);        }        if(sum<=0)        cout <<‘0‘ <<endl;        else printf("%d\n",sum);    }    return 0;}

 

[Two-segment continuous non-duplicate sequence and maximum] dynamic planning

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.