I learned a car a few days ago. I am really tired. I am tired of class. Now I can finally rest...
I have to repeat "Introduction to algorithms", but now I have to take it seriously. I have to look for a job in less than nine months. Just like my third-party, let's cheer up...
Introduction to AlgorithmsIt is through the stock purchase and sale, the previous day's stock price difference is re-expressed, that is, to a maximum sub array problemThe specific content is as follows:
13,-3,-25, 20,-3,-16,-23, 18, 20,-7, 12,-5,-22, 15,-4, 7
Find the continuous and maximum sub-arrays in the 16 consecutive numbers;
In the exercise section of the book, I used a non-recursive, linear time Algorithm for dynamic planning;
Starting from the left boundary of the array, processing from left to right records the largest child array that has been processed so far. If A [1 .. the largest subarray of j], based on the following properties, expands the solution to A [1... maximum sub-array of j + 1]: A [1... the maximum sub-array of j + 1] is either A [1... j], or A sub-array A [I... j + 1] (1 <= I <= j + 1 ). In the known A [1... in the case of the largest subarray of j], we can find the shape of A [I... the largest subarray of j + 1;
All the above ideas will come out. You just need to write down the key points:
If the preceding number and <0 are used, the addition of the following face array is not helpful. In this case, the array is reset.DpIsArray [I],And record start position;
If (dp [I-1] <= 0) // The preceding <0 directly discards {dp [I] = array [I]; temp = I; // record start time}
Otherwise, continue to extend;
Dp [I] = array [I] + dp [I-1]; // sum the following
The final result is to judge the maximum sub-array value and MarkStart position and end position:
If (dp [I]> MaxSumSub) // find the largest subarray up to I {MaxSumSub = dp [I]; // maximum... start = temp; // mark start end = I; // mark the end position at this time}
Code:
# Include
Using namespace std; int FindMaxSubarray (int array [], int length) {int start = 0, end = 0; // records the starting position of the largest subarray (subscript in the array) int MaxSumSub; // The maximum sub-array value int * dp = new int [length]; // dynamic planning record dp [0] = array [0]; // The first MaxSumSub = dp [0]; // The maximum value is the first int temp = 0; // for (int I = 1; I <length; I ++) {if (dp [I-1] <= 0) // The preceding <0 directly discards {dp [I] = array [I]; temp = I; // record start time} else dp [I] = array [I] + dp [I-1]; // sum the following if (dp [I]> MaxSumSub) // find the largest subarray up to I {MaxSumSub = dp [I]; // maximum... start = temp; // mark start end = I; // mark the end position} cout <"subscript of the largest subsequence:" <
<<"->
"<
<
The largest subsequence is{18, 20,-7, 12 };
The above dp is the process of searching the largest sub-array for dynamic records. You can also take a look at the output;
Thank you for your advice. o (∩ _ ∩) o
<
<<"->