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