Reputation: 131
The code below finds the biggest product pair, but it still doesn't make sure that the numbers are different and that the product is a multiple of 3.
let arr = [1, 4, 3, 6, 9, 9];
For instance, the answer for the above array should be 9x6=54 (product of the highest different numbers that is also multiple of 3) but my current code result is 9x9=81.
Important observation, the given array can contain positive and negative numbers also.
Does anyone have any tips?
// product in array of Integers
function maxProduct(arr, n)
{
// Sort the array
arr.sort(function(a, b){return a - b});
let num1, num2;
// Calculate product of two smallest numbers
let sum1 = arr[0] * arr[1];
// Calculate product of two largest numbers
let sum2 = arr[n - 1] * arr[n - 2];
// print the pairs whose product is greater
if (sum1 > sum2)
{
num1 = arr[0];
num2 = arr[1];
}
else
{
num1 = arr[n - 2];
num2 = arr[n - 1];
}
document.write("Max product pair = " +
"{" + num1 + "," + num2 + "}");
}
</script>
Upvotes: 0
Views: 1519
Reputation: 1
function maxProduct(arr) {
let a = 0;
let b = 0;
for(let i=0; i<=arr.length; i++){
if(a == 0){
if(arr[i]>a) a = arr[i];
} else {
if(arr[i]>a) {
b = a;
a = arr[i];
} else {
if(arr[i]>b) b = arr[i];
}
}
}
return a*b;
}
Upvotes: 0
Reputation: 8196
An O(N)
time, O(1)
extra space algorithm:
max_multiple_of_three
and min_multiple_of_three
largest_number_in_array
(which shouldn't be equal to max_multiple of three
) and smallest_number_in_array
(which shouldn't be equal to min_multiple_of_three
)max_multiple_of_three * largest_number_in_array
or min_multiple_of_three * smallest_number_in_array
Upvotes: 1
Reputation: 5287
You can do something like this:
multiples_of_3
(M3) and non_multiples_of_3
(NM3).This will always work for an array of positive numbers. If there are -ve numbers as well, then, -ve numbers will only be part of solution if both selected are -ve. In which case, you can repeat the steps for only -ve numbers in the input and compare.
Complexity: O(n) : 2 traversals, one to split the array into M3 and NM3, next to select largest M3 and 3 other candidates for +ve and -ve values.
Upvotes: 3