2.13 Maximum Product of the sub-array, 2.13 array Product
Question:
Given an integer array with the length of N, only multiplication is allowed and division is not allowed. The group that calculates the maximum product of any number of N-1 combinations.
Method 1:
# Include <iostream> # define MAXN 10000 using namespace std; int n, a [MAXN], s [MAXN], t [MAXN], p [MAXN]; // s [I] represents the product of the I elements before the array // t [I] represents the product of the N-I elements after the array // p [I] = s [I-1] * t [I + 1]; // p [I] indicates the product of other N-1 elements except the I element. // s [I] = A [0] * A [1] *… A [I], t [I] = A [I] * A [I + 1] *… A [N-1] // p [I] = s [I-1] * t [I + 1]. Int main () {cin> n; for (int I = 0; I <n; ++ I) cin> a [I]; int sv = 1, TV = 1; for (int I = 0; I <n; ++ I) {int j = n-i-1; sv * = a [I]; TV * = a [j]; s [I] = sv; t [j] = TV;} int maxNum = p [0] = t [1]; // p [0] and t [1] indicate the value of the remaining N-1 elements, except the first element. For (int I = 1; I <n; ++ I) {p [I] = s [I-1] * t [I + 1]; maxNum = maxNum <p [I]? P [I]: maxNum;} cout <maxNum <endl; return 0 ;}
Method 2:
Ideas:
The maximum product of sub-arrays can be divided into the following situations.
1. if there is more than one zero in the array, the maximum product is 0;
2. There is only one zero in the array, and there are odd negative numbers, the maximum product must be 0;
3. If there is only one zero element in the array and an even negative number exists, the maximum product is the product of the element except 0;
4. If there is no zero in the array and there are odd negative numbers, the maximum product is the product that removes the negative number of the smallest absolute value;
5. If there is no zero in the array and an even negative number exists, the maximum product is the product that removes the smallest positive number.
So we can find the number of positive numbers, the number of negative numbers, and the number of 0 in the array! This is the simplest method!