And largest subsequences-Dynamic Planning, sequence-Planning

Source: Internet
Author: User

And largest subsequences-Dynamic Planning, sequence-Planning
Problem description for A given integer sequence A whose length is N, its "subsequence" is defined as A consecutive element (integer) that is not null in ). The task you want to complete is to find a sub-sequence among all possible sub-sequences. The sum of all elements in the sub-sequence is the largest (compared with all other sub-sequences ). The program requires you to output the maximum value. The first line of the input file contains an integer N, and the second line contains N integers, indicating.
Where
1 <= N <= 100000
-10000 <= A [I] <= 10000 the output format contains only one integer, indicating the answer you calculated. Sample input 53-2 3-5 4 sample output 4
I think there are two solutions to this problem: Simulation + greedy and dynamic planning. For the first one, I think the amount of code is large, so I chose the second method to solve this problem. In fact, the state transition equation of this question is well determined.D [I] = max (d [I-1] + a [I], 0); D [I] represents the sum of the largest continuous subsequences at the position I, and a [I] represents the value of a layer loop at the position I, which is very simple.

# Include <stdio. h ># include <algorithm> using namespace std; int a [100005]; int d [100005]; int main () {int n; scanf ("% d ", & n); for (int I = 1; I <= n; I ++) {scanf ("% d", & a [I]);} int maxn = 0; for (int I = 1; I <= n; I ++) {d [I] = max (d [I-1] + a [I], 0); if (d [I]> maxn) maxn = d [I];} printf ("% d \ n", maxn); 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.