Dynamic Planning question (3) -- maximum continuous product substring, planning product
Dynamic Planning question (3) -- maximum continuous product substring
1. Description
For a floating point number sequence, obtain the maximum product continuous substring value, for example,-2.5, 0.5, 3, 8,-1. The maximum product continuous substring is 3, 0.5, 8. That is to say, in the preceding array, the product 0.5 = 12 of the three numbers of 3 30.58 8 is the largest and continuous.
2. Dynamic Planning
When dynamically planning and solving a question, the most important thing is to find the state transfer equation!
For this question, we use two variables to record the current maximum value maxEnd and the current minimum value minEnd. Why is the current minimum value recorded? The array contains a negative number. If you multiply it by a negative number, the current minimum value is reversed !!
Then there is an update to the two variables in the state transition equation:
MaxEnd = max (maxEnd * a [I], minEnd * a [I]), a [I]); // update the current maximum value
MinEnd = min (maxEnd * a [I], minEnd * a [I]), a [I]); // update the current minimum value
The time complexity of the following solution is O (n ).
The Code is as follows:
# Include <iostream> # include <algorithm> # define max (a, B) (a)> (B ))? (A): (B) // macro definition. Note that brackets are added. # define min (a, B) (a) <(B ))? (A): (B) using namespace std; double findMaxProduct (double * a, int num) {double maxProduct = a [0]; double maxEnd = a [0]; // record the current maximum value of double minEnd = a [0]; // record the current minimum value, because a negative number will appear later, the current minimum value will be reversed ~! For (int I = 1; I <num; I ++) {maxEnd = max (maxEnd * a [I], minEnd * a [I]), a [I]); // update the current maximum value minEnd = min (maxEnd * a [I], minEnd * a [I]), a [I]); // update the current minimum value maxProduct = max (maxEnd, maxProduct); // the maximum value of the product must be either of the two} return maxProduct;} int main () {double a [7] = {-2.5, 4, 0, 3, 0.5, 8,-1}; int num = 7; double maxProduct = findMaxProduct (a, num ); cout <maxProduct <endl ;}