fork(1) download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. // Function to find maximum product of two integers in an array
  5. void findMaximumProduct(int arr[], int n)
  6. {
  7. // Find maximum and second maximum element in an array
  8. int max1 = arr[0], max2 = INT_MAX;
  9.  
  10. // Find minimum and second minimum element in an array
  11. int min1 = arr[0], min2 = INT_MAX;
  12.  
  13.  
  14. // Traverse an array one time to find max1 , max2 , min1 , min2
  15. for (int i = 1; i < n; i++)
  16. {
  17. // if current element is more than the maximum element,
  18. // update maximum and second maximum element
  19. if (arr[i] > max1)
  20. {
  21. max2 = max1;
  22. max1 = arr[i];
  23. }
  24.  
  25. // if current element is less than maximum but greater than second
  26. // maximum element, update second maximum element
  27. else if (arr[i] > max2)
  28. {
  29. max2 = arr[i];
  30. }
  31.  
  32. // else ignore the element
  33.  
  34. // if current element is more than the minimum element,
  35. // update minimum and second minimum element
  36. if (arr[i] < min1)
  37. {
  38. min2 = min1;
  39. min1 = arr[i];
  40. }
  41.  
  42. // if current element is less than minimum but greater than second
  43. // minimum element, update second minimum element
  44. else if (arr[i] < min2)
  45. min2 = arr[i];
  46.  
  47. // else ignore the element
  48. }
  49.  
  50.  
  51. // Maximum product is formed by maximum of
  52. // 1. product of maximum and second maximum element or
  53. // 2. product of minimum and second minimum element
  54. if (max1 * max2 > min1 * min2)
  55. printf("Pair is (%d, %d)", max1, max2);
  56. else
  57. printf("Pair is (%d, %d)", min1, min2);
  58. }
  59.  
  60. // main function
  61. int main()
  62. {
  63. int arr[] = { -10, -3, 5, 6, -2 };
  64. int n = sizeof(arr) / sizeof(arr[0]);
  65.  
  66. findMaximumProduct(arr, n);
  67.  
  68. return 0;
  69. }
Success #stdin #stdout 0s 2740KB
stdin
Standard input is empty
stdout
Pair is (-10, -3)