Problem Statement:
You are given a unsorted array of distinct integers, you need to find the largest pair sum
Example:
Input: [1, 4, 3, 2, 5]
Output: 9
Solution 1: Brute force approach
Idea is to use 2 nested loops and then iterate over all the pairs in the array and keep track of the max sum and return the result.
Time Complexity: O(n^2)
Space Complexity: O(1)
Solution 2: Efficient approach
In this approach, we will find the largest and second largest element in the array.
Then return the sum of the 2 elements.
Time Complexity: O(n)
Space Complexity: O(1)
Code Solution
#include <iostream>
#include <vector>
using namespace std;
int solution_2 (vector<int>& arr, int n)
{
if (n < 2)
return -1;
int first, second;
if (arr[0] > arr[1])
{
first = arr[0];
second = arr[1];
}
else
{
first = arr[1];
second = arr[0];
}
for (int i = 2; i < n; i++)
{
if (arr[i] > first)
{
second = first;
first = arr[i];
}
else if (arr[i] > second)
second = arr[i];
}
return (first + second);
}
int solution_1 (vector<int> &arr, int n)
{
int maxSum = 0;
for (int i = 0; i < n - 1; i++)
{
for (int j = i + 1; j < n; j++)
{
int sum = arr[i] + arr[j];
if (sum > maxSum) {
maxSum = sum;
}
}
}
return (maxSum == 0)? -1 : maxSum;
}
int main()
{
vector<int> arr = { 1, 4, 3, 2, 5 };
int n = arr.size();
cout << "Solution 1 = " << solution_1(arr, n)<<endl;
cout << "Solution 2 = " << solution_2(arr, n)<<endl;
return 0;
}
Output
Solution 1 = 9
Solution 2 = 9