Maximum subsequence Product
Maximum sub-sequence product problem
Maximum Product Subarray 2014.10.13
Question description (from leetcode, question)
Find the continuous subsequence of a sequence so that the product reaches the maximum (containing at least one element) and return the maximum product.
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example:
Given a sequence [2, 3,-2, 4], a continuous subsequence [2, 3] has a maximum product of 6.
Given sequence [3,-1, 4], continuous subsequence [4] has a maximum product equal to 4.
Algorithm 1:
We know that there is a time complexity when finding the maximum subsequence sum:O (N ^ 3)The running time isO (N ^ 3)Because of its efficiency, it is usually not used. To better understand this problem, we first give the algorithm program.
Code
/** Maximum subsequence product O (N ^ 3) algorithm * Cubic maximum contiguous subsequence product algorithm */int maxSubProduct1 (int A [], int n) // input the array address and number of elements {if (n = 0) return 0; int maxPro = 1; // Save the result for (int I = 0; I <n; I ++) {for (int j = I; j <n; j ++) {int thisPro = 1; // save A [I] *... * result of A [j] for (int k = I; k <= j; k ++) thisPro * = A [k]; if (thisPro> maxPro) maxPro = thisPro; }}return maxPro ;}
Algorithm 2:
Because we do not need to know where the best sub-sequence is, we can improve algorithm 1 as follows. The time complexity of the improved algorithm isO (N ).
We know that the sequence element A [I] may be negative, while the negative is positive. Therefore, we should not only keep the maximum sequence product before A [I], but also keep the minimum sequence product.
Therefore, we define the maximum sequence product next to A [I] before A [I] As maxPre, and the smallest sequence product next to A [I] before A [I] As minPre, the maximum sequence product before A [I] Is maxhere.
We only need to scan the data once. Once A [I] is processed, it will no longer need to be remembered and complete the following steps until the end of I is n:
MaxPre = max (maxPre * A [I], minPre * A [I], A [I]); minPre = min (maxPre * A [I], minPre * A [I], A [I]); maxhere = max (maxhere, maxPre );
/** Maximum subsequence product O (N) algorithm * Linear-time maximum contiguous subsequence product algorithm */int maxSubProduct2 (int A [], int n) {if (n = 0) return 0; int maxPre = A [0]; // The maximum product of the adjacent subsequences before the element int minPre = A [0]; // int maxhere = A [0], the smallest product of the adjacent subsequence before the element; // The storage result int temp; for (int I = 1; I <n; I ++) {temp = maxPre; // first save the maxPre value maxPre = max (maxPre * A [I], minPre * A [I]), A [I]); minPre = min (temp * A [I], minPre * A [I]), A [I]); if (maxPre> maxhere) maxhere = maxPre ;} return maxhere ;}
Be a person who has some requirements for himself.
Zookeeper