Description:
Given an integer array a [n], calculate the maximum product of any n-1 elements in the array. Division is not allowed, and time complexity O (n) is not allowed ), space complexity O (1 ).
Idea: obtain the maximum and minimum positive numbers in the array, and then multiply the number of other numbers. If the product is a negative number, multiply it by the maximum negative number. If the product is a positive number, multiply it by the minimum positive number.
[Cpp]
# Define MAX 0x7FFFFFFF
Int maxMulit (int * a, int n ){
If (a = NULL | n <= 0) return 0;
Int minp = 0, minn = 0, maxsum = 1, max =-MAX, min = MAX;
// Obtain the subscript of the minimum positive number and the maximum negative number.
For (int I = 0; I <n; ++ I ){
If (a [I]> = 0 & a [I] <min ){
Minp = I;
Min = a [I];
}
Else if (a [I] <0 & a [I]> max ){
Minn = I;
Max = a [I];
}
}
For (int I = 0; I <n; I ++ ){
If (I! = Minn & I! = Minp ){
Maxsum * = a [I];
}
}
If (maxsum> 0) maxsum * = a [minp];
Else maxsum * = a [minp];
Return maxsum;
}
# Define MAX 0x7FFFFFFF
Int maxMulit (int * a, int n ){
If (a = NULL | n <= 0) return 0;
Int minp = 0, minn = 0, maxsum = 1, max =-MAX, min = MAX;
// Obtain the subscript of the minimum positive number and the maximum negative number.
For (int I = 0; I <n; ++ I ){
If (a [I]> = 0 & a [I] <min ){
Minp = I;
Min = a [I];
}
Else if (a [I] <0 & a [I]> max ){
Minn = I;
Max = a [I];
}
}
For (int I = 0; I <n; I ++ ){
If (I! = Minn & I! = Minp ){
Maxsum * = a [I];
}
}
If (maxsum> 0) maxsum * = a [minp];
Else maxsum * = a [minp];
Return maxsum;
}