Problem description: given an integer sequence (which may have positive numbers, 0 and negative numbers), calculate the product of a continuous maximum subsequence. if the product is negative, the output is-1.
Analysis: 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 [1] = min [1] = A [1]. The Code is as follows:
/* Given an integer array consisting of positive and negative numbers, 0 and positive numbers, the array subscript calculates the product of the maximum continuous subsequence from 1 and outputs this sequence, if the product of the maximum subsequence is negative, in this case, output-1 uses MAX [I] to represent the continuous subsequences with the largest product ending with a [I] And Min [I] to represent the continuous subsequences with the smallest product ending with a [I ]. because there are plural numbers, therefore, saving this is required */
Void longest_multiple (int * a, int N) {int * min = new int [n + 1] (); int * max = new int [n + 1] (); int * P = new int [n + 1] (); // initialize for (INT I = 0; I <= N; I ++) {P [I] =-1;} min [1] = A [1]; Max [1] = A [1]; int max_val = MAX [1]; for (INT I = 2; I <= N; I ++) {max [I] = max (I-1] * A [I], min [I-1] * A [I], a [I]); Min [I] = min (MAX [I-1] * A [I], min [I-1] * A [I], a [I]); If (max_val <MAX [I]) max_val = MAX [I];} If (max_val <0) printf ("% d",-1); else printf ("% d", max_val); // memory release Delete [] Max; Delete [] min ;}