Maximum sub-array and

Source: Internet
Author: User

Title Description

Given an array a[0,..., n-1], find its maximum subarray (length >=1) and


Enter a description

First line an integer n (1<=n<=5000), and then enter n integers (each integer range [-5000, 5000])


Output description

Outputs an integer representing the maximum number of sub-arrays and


Sample input

51-1 1 1-1


Sample output

2




Of course there are search or enumeration and so on, O (n) algorithm can be used DP.

Set Sum[i] is the contiguous subarray with the end of the first element and the largest.
Assuming that for element I, all the lengths of the sub-arrays that end with its preceding elements have been evaluated, then the contiguous subarray that ends with the first element and the largest is actually either the i-1 of the first element and the largest contiguous subarray plus the element, or it contains only the I-element, or sum[i] = max ( SUM[I-1] + a[i], a[i]).
The choice can be made by judging whether Sum[i-1] + a[i] is greater than a[i], which is actually equivalent to judging whether sum[i-1] is greater than 0.
Since each operation requires only the previous result, it is not necessary to keep all the previous results as normal dynamic planning, only the last one, so the algorithm has very little time and space complexity.

The code is as follows:
1#include <iostream>2 using namespacestd;3 4 intMain ()5 {6     intn, num;7     Longsum, max;8CIN >>N;9CIN >>sum;TenMax =sum; One      for(inti =1; I < n; i++) A     { -CIN >>num; -         if(Sum >0) theSum + =num; -         Else -sum =num; -         if(Sum >max) +Max =sum; -     } +  Acout <<Max; at  -     return 0; -}

Reference:http://www.cnblogs.com/waytofall/archive/2012/04/10/2439820.html

Maximum sub-array and

Related Article

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.