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