Prove safety offer30: sub-continuous array of maximum and

1 Title Description

  HZ occasionally get some professional issues to flicker those non-computer science students. After the test group will finish today, he spoke up: in the old one-dimensional pattern recognition, it is often necessary to calculate the maximum and continuous sub-vector when the vector is a positive whole number, the problem solved. However, if the vector contains a negative number, it should contain a negative number, and expect a positive number next to it would make up for it? For example: {6, -3, -2,7, -15,1,2,2}, and the maximum successive sub-vectors of 8 (beginning from 0, up to the third). To an array and returns its maximum continuous subsequence and you will not be fooled him live? (Sub-vector length is at least 1).

2 ideas and methods, C ++ core code

2.1 max function

int temp_max = array[0];
int max_num = array[0];
for(int i=1;i<array.size();i++){
  temp_max = max(array[i], array[i]+temp_max);
  max_num = max(temp_max, max_num);
}
return max_num;

2.2 endMaxSum represents the current maximum continuous sub-element and the end of the sequence; when endMaxNum <0, the endMaxNum = array [i] otherwise endMaxNum + = array [i]

. 1  IF (array.empty ())
 2  return  0 ;
 . 3  IF (array.size () == . 1 )
 . 4  return Array [ 0 ];
 . 5  
. 6  int maxSum = Array [ 0 ]; // maximum continuous subsequence and 
7  int endMaxSum = maxSum; // current maximum consecutive sub-sequences and at the end of the element 
. 8  for ( int I = . 1 ; I <array.size (); ++ I) {
 . 9  IF (endMaxSum> 0 )
 10 endMaxSum + = Array [I];
 . 11 else 
12 endMaxSum = array [i];
13  if (endMaxSum> )
 = 14 endMaxSum;
15  }
 16  return ;
View Code

Reference material

https://blog.csdn.net/zjwreal/article/details/88608962

Guess you like

Origin www.cnblogs.com/wxwhnu/p/11415928.html