This is a high probability in the interview of a topic, take me to say, interviewed 5 companies, two companies asked this topic, it can be seen that the topic is very classic.
The thought of solving problems is not very difficult, I am familiar with, two ways to solve the problem:
1. Continuous addition, the condition of terminating the current sequence is a plus and a negative number
Because, a number plus a negative value is definitely not the original values, so, this is certainly meaningless, and finally, we use this idea to get the following solution.
function declaration:
ll Dutmaxseqsubarray_1 (int*, int.);
typedef long Long LL;
Source:
/* A very common solution for the largest contiguous subarray */bool _dutmaxseqsubarray = False;ll dutmaxseqsubarray_1 (int* A, int size) {if (! A | | Size <= 0) {_dutmaxseqsubarray = true;return-1;} ll result = 1 << 31;ll currentsum = 0;/* loop through the array, the next round of Add and */for (int i = 0; i < size; ++i) {if (Currentsum & lt;= 0) Currentsum = a[i];elsecurrentsum + = a[i];if (Result < Currentsum) result = currentsum;} return result;}
2. The idea of dynamic planning: Continuous Subarray Max and must also end with a certain value
Regardless of the number of successive sub-arrays, no matter how big it is, it always ends with a number, and that number definitely appears in the array, so you can get the following recursive formula:
The sum of the largest contiguous subarray ending in the current number is:
Pdata[i] = Pdata[i-1] + a[i] | | A[i]
Therefore, the following solutions can be obtained:
function declaration:
ll Dutmaxseqsubarray_2 (int*, int.);
Source:
/* Solution for Dynamic programming */ll dutmaxseqsubarray_2 (int* A, int size) {if (! A | | Size <= 0) {_dutmaxseqsubarray = true;return-1;} ll result = 1 << 31;ll currentsum = 0;for (int i = 0; i < size; ++i) {/* * The idea is that the maximal contiguous subarray must end with an array element, so * at the end of that number The maximum sum of the sum of the entire array can be obtained */currentsum = dutmax<ll> (Currentsum + a[i], a[i]); result = dutmax<ll> (result, Currentsum);} return result;}
The template function used:
Template <typename t>t Dutmax (t data1, T data2) {return data1 > data2? data1:data2;}
The beauty of programming 2.14 to find the maximum of the sum of the array's sub-arrays