Maximum Sum pair of non adjacent elements in array
Given an array arr[] of distinct Integers, find the pair with maximum sum such that both elements of the pair are not adjacent in the array
Examples:
Input: arr[] = {7, 3, 4, 1, 8, 9}
Output: 9 7
Explanation: Pair with maximum sum is (8, 9).
But since both elements are adjacent, it is not a valid pair.
Therefore, the pair with maximum sum is (9, 7) with sum 16.Input: arr[] = {2, 1, 3}
Output: 2 3Input: arr[] = {4, 3, 7, 9, 8, 1}
Output: 7 8
Explanation: Sum of both the pairs {7, 9} and {9, 8} are greater.
But they are adjacent pairs. Hence this is the valid answer.
Approach: The Idea is to compute the indices of the largest three elements in the array. After computing the indices, check the pair with max sum and also check whether they are adjacent or not. It is always possible to get at least one pair with two elements that are not adjacent as the three largest elements have been computed.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the max pair sum// which are non-adjacentpair<int, int> getMaxSumPair(int arr[], int N){ // Indices for storing first, second // and third largest element if (N < 3) { return make_pair(-1, -1); } int first, second, third; if (arr[1] > arr[0]) { if (arr[1] > arr[2]) { first = 1; if (arr[2] > arr[0]) { second = 2; third = 0; } else { second = 0; third = 2; } } else { first = 2; second = 1; third = 0; } } else { if (arr[0] > arr[2]) { first = 0; if (arr[2] > arr[1]) { second = 2; third = 1; } else { second = 1; third = 2; } } else { first = 2; second = 0; third = 1; } } for (int i = 3; i < N; ++i) { if (arr[i] > arr[first]) { third = second; second = first; first = i; } else if (arr[i] > arr[second]) { third = second; second = i; } else if (arr[i] > arr[third]) { third = i; } } // Check whether the elements // are adjacent or not if (abs(first - second) == 1) { if (abs(first - third) == 1) { return make_pair(arr[second], arr[third]); } else { return make_pair(arr[first], arr[third]); } } else { return make_pair(arr[first], arr[second]); }} // Driver Codeint main(){ int arr[] = { 7, 3, 4, 1, 8, 9 }; int N = sizeof(arr) / sizeof(*arr); pair<int, int> p = getMaxSumPair(arr, N); cout << p.first << " " << p.second; return 0;} |
9 7
Time Complexity: O(N)
Auxiliary Space: O(1)


.png)