## Thursday, August 11, 2016

### Find a pair with maximum product in array of Integers - GeeksforGeeks

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.

`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 << ``"}"``;`
`}`
Find a pair with maximum product in array of Integers 找出数组中最大乘积的一对

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};
}