869923. Largest Pair Sum
Easy
Largest Pair Sum
Slug: pair-sum--120604
Difficulty: Easy
Id: 869923
Topic Tags: two-pointer-algorithm, Arrays, Searching
Company Tags: None
Summary
Given an array of integers, the task is to find the largest pair sum possible by choosing any two elements from the given array. This problem involves searching and sorting techniques.
Detailed Explanation
To solve this problem, we can use a simple algorithm that iterates through the array once. We maintain two pointers, one at the start of the array and one at the end. At each step, we compare the values at these positions and update our pair sum accordingly.
Here's the step-by-step breakdown:
- Initialize two pointers,
startandend, to the first and last elements of the array respectively. - Compare the values at
startandend. - If
startis smaller thanend, updatepair_sumwith the sum of these two values and movestartone step forward. - If
endis smaller thanstart, updatepair_sumwith the sum of these two values and moveendone step backward. - Repeat steps 2-4 until
startmeets or crossesend. - The final value of
pair_sumis the largest possible pair sum.
The time complexity of this algorithm is O(n), where n is the size of the input array, as we only need to iterate through the array once. The space complexity is O(1) since we're not using any additional space that scales with the input size.
Optimized Solutions
Java
public int largestPairSum(int[] arr) {
if (arr.length < 2) return -1; // edge case
int start = 0, end = arr.length - 1;
int pair_sum = Integer.MIN_VALUE;
while (start <= end) {
if (arr[start] > arr[end]) {
pair_sum = Math.max(pair_sum, arr[start] + arr[end]);
start++;
} else {
pair_sum = Math.max(pair_sum, arr[start] + arr[end]);
end--;
}
}
return pair_sum;
}