This seems to be similar to Max subarray, but it is only the addition and multiplication method that has tried to use the division method, which is especially troublesome to find the division. So I analyzed the characteristics of this question:
1. Sensitive to 0. Once there is 0, the product will not change. Therefore, you need to split the array when there is 0.
2. If there is no 0, the absolute value will definitely increase after multiplication, so only the question of positive and negative numbers is enough.
If the multiplication of the entire array is a positive number, then the maximum value is undoubtedly obtained, but what should I do when the multiplication is a negative number?
In consideration, the only way is to reduce a negative number. In this case, either the leftmost negative number or the rightmost negative number (the array must be continuous and start from both sides ).
When the negative number on the left is removed, the product should start from left + 1 (left is the index with the negative number on the left)
When the negative number on the right is removed, the product should be until right-1.
I don't know if I think too much about the complexity or implementation, and my code is not very concise:
int maxProduct(int A[], int n) {if (n == 1)return A[0];int i = 0;int result = 0;while (i < n){int left = -1;int right = -1;int product = 1;while (i < n && A[i] == 0)i++;if (i == n) break;int start = i;while (i < n && A[i] != 0){product *= A[i];if (left == -1 && A[i] < 0)left = i;if (A[i] < 0)right = i;i++;}if (product > 0){if (product > result)result = product;}else {int leftprod = 1;int rightprod = 1;bool flagl = false;for (int index = start; index < right; index++){leftprod *= A[index];flagl = true;}bool flagr = false;for (int index = left + 1; index < i; index++){rightprod *= A[index];flagr = true;}if (flagl && flagr && max(leftprod, rightprod) > result)result = max(leftprod, rightprod);if (flagl && !flagr) {result = max(leftprod, result);}if (flagr && !flagl) {result = max(rightprod, result);}}}return result;}
Maximum Product subarray