Maximum continuous sub-sequence product, continuous sub-sequence Product
Problem description
Given an integer sequence (which may have positive numbers, 0 and negative numbers), calculate its maximum continuous subsequence product. For example, if an array a = {3,-4,-5, 6,-2} is given, the maximum continuous subsequence product is 360, that is, 3 * (-4) * (-5) * 6 = 360.
Analysis
The product of the maximum continuous subsequence is different from that of the maximum continuous subsequence, because positive, negative, or zero.
Assume that the array is a [] and the dynamic return is used directly to solve the problem. Considering the possible negative number, we use Max [I] to represent the product value of the maximum continuous subsequence ending with a [I, min [I] indicates the product value of the smallest continuous subsequence ending with a [I]. The state transition equation is:
Max [I] = max {a [I], Max [I-1] * a [I], Min [I-1] * a [I]}; min [I] = min {a [I], Max [I-1] * a [I], Min [I-1] * a [I]}; the initial status is Max [0] = Min [0] = a [0]. The Code is as follows:
Int max_multiple (int * a, int n) {int * Min = new int [n] (); int * Max = new int [n] (); min [0] = Max [0] = a [0]; int max = Max [0]; for (int I = 1; I <n; I ++) {Max [I] = max3 (Max [I-1] * a [I], Min [I-1] * a [I], a [I]); // calculate the maximum value Min [I] = min3 (Max [I-1] * a [I], Min [I-1] * a [I], a [I]); // calculate the minimum value of the three values, if (max <Max [I]) max = Max [I];} // memory release delete [] Max; delete [] Min; return max ;}
If you do not need an array, you can use a temporary variable to save the maximum and minimum values of the last time. The Code is as follows:
int max_multiple_2(int *a,int n) { int minsofar, maxsofar, max; max = minsofar = maxsofar = a[0]; for(int i=1;i<n;i++){ int maxhere = max3(maxsofar*a[i], minsofar*a[i], a[i]); int minhere = min3(maxsofar*a[i], minsofar*a[i], a[i]); maxsofar = maxhere, minsofar = minhere; if(max < maxsofar) max = maxsofar; } return max; }
Add the max3 code of the function for finding the maximum number of three:
int max3(int a, int b, int c) { if (a>=b && a>=c) return a; return max3(b, c, a); }