Reputation: 21
I tried the optimized solution but unable to solve some errors present in geeks for geeks when submitted. It seems to work for the most of test cases.
class Solution {
int maxProduct(int arr[], int n) {
// code here
int max1,max2;
max1 = max2 = 1;
for(int i=0;i<n;i++){
if(max1<arr[i]){
max2=max1;
max1=arr[i];
}
}
return max1 * max2;
}
}
Upvotes: 2
Views: 187
Reputation: 128
You simply need to add a second if conditional parameter: if( max1 < arr[i] || max2 < arr[i] )
because you won't always find a new max, but you might find a new second max. Also with what Somnath said in his reply, you could also encounter negatives, so I suggest using max1 = max2 = Integer.MIN_VALUE
to avoid any arbitrary negative interference.
Edit: As a slight refactoring, remove the parameter n
from your method and in the for loop's conditional evaluation, simply use i < arr.length
Upvotes: 0
Reputation: 50
If -8,-7,0,1,5
is your array, what would be max product of two numbers in your array?
Think about this test case
Upvotes: 1