Problem 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?
Algorithm analysis
There is a temp for Pathfinder, sum is responsible for saving the final value, initially an array of the first number;
In every round of cycle,
Temp is the current number if it is less than 0, otherwise temp equals temp plus the current number;
Then compare the size of sum and temp, sum equals the big one.
Code implementation
classSolution { Public:intFindgreatestsumofsubarray ( vector<int> Array) {if(Array. Size () = =0)return 0;intsum =Array[0];inttemp =Array[0]; for(intI=1;i<Array. Size (); i++) {temp = (temp<0?Array[I]:Array[I]+temp]; sum = max (sum, temp); }returnSum }};
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
The largest and most consecutive sub-arrays of "Jian Zhi"