Find a pair with maximum product in array of Integers - GeeksforGeeks
Given an array with both +ive and -ive integers, return a pair with highest product.
An Efficient Solution can solve the above problem in single traversal of input array. The idea is to traverse the input array and keep track of following four values.
a) Maximum positive value
b) Second maximum positive value
c) Maximum negative value i.e., a negative value with maximum absolute value
d) Second maximum negative value.
At the end of the loop, compare the products of first two and last two and print the maximum of two products.
Find a pair with maximum product in array of Integers 找出数组中最大乘积的一对
Given an array with both +ive and -ive integers, return a pair with highest product.
An Efficient Solution can solve the above problem in single traversal of input array. The idea is to traverse the input array and keep track of following four values.
a) Maximum positive value
b) Second maximum positive value
c) Maximum negative value i.e., a negative value with maximum absolute value
d) Second maximum negative value.
At the end of the loop, compare the products of first two and last two and print the maximum of two products.
void
maxProduct(
int
arr[],
int
n)
{
if
(n < 2)
{
cout <<
"No pairs exists\n"
;
return
;
}
if
(n == 2)
{
cout << arr[0] <<
" "
<< arr[1] << endl;
return
;
}
// Iniitialize maximum and second maximum
int
posa = INT_MIN, posb = INT_MIN;
// Iniitialize minimum and second minimum
int
nega = INT_MIN, negb = INT_MIN;
// Traverse given array
for
(
int
i = 0; i < n; i++)
{
// Update maximum and second maximum if needed
if
(arr[i] > posa)
{
posb = posa;
posa = arr[i];
}
else
if
(arr[i] > posb)
posb = arr[i];
// Update minimum and second minimum if needed
if
(arr[i] < 0 &&
abs
(arr[i]) >
abs
(nega))
{
negb = nega;
nega = arr[i];
}
else
if
(arr[i] < 0 &&
abs
(arr[i]) >
abs
(negb))
negb = arr[i];
}
if
(nega*negb > posa*posb)
cout <<
"Max product pair is {"
<< nega <<
", "
<< negb <<
"}"
;
else
cout <<
"Max product pair is {"
<< posa <<
", "
<< posb <<
"}"
;
}
但是上面的例子不能完全说明问题, 比如说{0,1,-5}, 这时候, pair应该是0, 1 OR 0, -5.
思路很简单, 通过观察上面的例子, 不难发现, 这个pair和四个数字有关: 数组中, 正数的最大值pmax和第二大值psec, 负数的最大值nmax和第二大值nsec. 而最大值应为Math.max(pmax*psec, nmax*nsec).
需要注意的是else if在判断时候使用, 还有初始化时,应该把值初始为0.
public int[] find(int[] nums) {
if (nums == null || nums.length == 0)
return new int[]{};
int[] res= new int[2];
int pmax= 0,psec = 0; //pmax 是positive最大,psec是第二大
int nmax= 0,nsec = 0; //nmax 是negative最小,nsec是第二小
for (int i = 0; i < nums.length; i++) {
if (nums[i] > 0){
if (nums[i] > pmax) {
psec = pmax; // 更新max时, 要把max给sec.
pmax = nums[i];
}
else if (nums[i] > psec)
psec = nums[i];
}
else if (nums[i] < 0) {
if (nums[i] < nmax) {
nsec = nmax;// 更新max时, 要把max给sec.
nmax = nums[i];
}
else if (nums[i] < nsec)
nsec = nums[i];
}
}
if (pmax*psec > nmax*nsec)
return new int[]{pmax,psec};
else
return new int[]{nmax,nsec};
}
Read full article from Find a pair with maximum product in array of Integers - GeeksforGeeks