Sword Point Offer (30) maximum value of continuous sub-array

Source: Internet
Author: User

Title Description

Hertz occasionally takes some professional questions to confuse students who are not computer majors. Today, the test team after the meeting, he said again: in the Ancient one-dimensional pattern recognition, it is often necessary to calculate the maximum sum of continuous sub-vectors, when the vector is all positive, the problem is well solved. However, if the vector contains a negative number, should it contain a negative number and expect that the next positive number will compensate for it? For example: {6,-3,-2,7,-15,1,2,2}, the maximum and 8 of continuous sub-vectors (starting from No. 0 to 3rd). Will you be fooled by him? (The length of the sub-vector is at least 1)

Problem analysis

This problem we can analyze the array, one of the law. However, if you know the dynamic planning, it is easy to find that the following results are related to the previous. If a function sum (i) is used to denote the maximum sum of the sub-arrays ending with the number I, then we only need to ask the

Max[sum (i)], where the following recursive formula can be used.

When i=0, or sum (i-1) <=0, sum (i) =array[i];

When i≠0, or sum (i-1) >0, sum (i) =sum (i-1) +array[i];

Then we can write the code.

Code
function Findgreatestsumofsubarray (array) {    ifreturn 0;    Let sum=array[0],max=array[0];      for (Let i=1;i<array.length;i++) {        if(sum<0) sum=array[i];         else sum=sum+array[i];         if (sum>max) max=sum;    }     return Max;}

Sword Point Offer (30) maximum value of continuous sub-array

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.