Input given is an int array, which may or may not contain positive, negative or zero values. Write a program to find out the two numbers which gives the highest product. (Both numbers should be positive or negative.)
Below is my code whose time complexity is O(n2), I believe. Is there any improvement I can make to the code?
public class FindLargestProduct{
public static void main(String[] args) {
int[] arr = { 52, 12, 34, 10, 6, 40, 0, 12, 40, 52, -56, -78, -99, 68 };
int firstMax = 0, secondMax = 0;
int firstNegMax = 0, secondNegMax = 0;
for (int i = 0; i < arr.length; ++i) {
if (arr[i] > 0) {
if (arr[i] > firstMax) {
secondMax = firstMax;
firstMax = arr[i];
} else if (arr[i] > secondMax) {
secondMax = arr[i];
}
}
if (arr[i] < 0) {
secondNegMax = firstNegMax;
firstNegMax = arr[i];
if (arr[i] > firstNegMax) {
secondNegMax = firstNegMax;
firstMax = arr[i];
} else if (arr[i] > secondNegMax) {
secondNegMax = arr[i];
}
}
}
int proPositive = firstMax * secondMax;
int proNegative = firstNegMax * secondNegMax;
if (proPositive > proNegative) {
System.out.println(proPositive);
} else {
System.out.println(proNegative);
}
}
}
both numbers should be (positive or negative)
or 2.(both numbers should be positive) or (both numbers should be negative)
? Is zero ever a valid number when calculating the result? Is mixing one positive and one negative allowed? \$\endgroup\$