Dynamic Programming Topic (III.)--maximal continuous product substring
1. Title Description
Given a sequence of floating-point numbers, taking the value of the maximal product continuous substring, such as -2.5,4,0,3,0.5,8,-1, the maximum product continuous substring fetched is 3,0.5,8. That is, in the above array, 3 0.5 8 The product 30.58=12 of the 3 numbers is the largest, and is continuous.
2. Dynamic Solver
The most important thing when solving the problem of dynamic programming is to find the state transition equation!
For this topic, we use two variables to record the current maximum value of maxend, and the current minimum value of minend. Why record the current minimum value? Because there will be negative numbers in the array, multiplied by a negative number, the current minimum is the reverse attack!!
Then there is the update of these two variables in the state transition equation:
Maxend=max (Max (Maxend*a[i], minend*a[i]), a[i]); Update current maximum value
Minend=min (min (maxend*a[i], minend*a[i]), a[i]); Update current minimum value
The following solution has a time complexity of O (n).
The code is as follows:
#include <iostream> #include <algorithm> #define MAX (A, B) (((a) > (b))? (a): (b) //macro definition, note the parentheses # # 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 current maximum value double minend=a[0]; Record the current minimum value, because there will be negative after the current minimum value will be reversed! for (int i=1; i<num; i++) {Maxend=max (max (Maxend*a[i], minend*a[i]), a[i]); Update current maximum value minend=min (min (maxend*a[i], minend*a[i]), a[i]); Update current minimum value Maxproduct=max (Maxend, maxproduct); The maximum value of the product must be two to select a}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<<MAXP roduct<<endl; }
Dynamic Programming Topic (III.)--maximal continuous product substring