Leetcode 2815. Max Pair Sum in an Array
Given an array of integers nums
, find the maximum sum of any pair of integers in the array where the two integers are not adjacent to each other.
Input: nums = [3, 5, 2, 3, 7, 1]
Output: 10
Explanation: The maximum pair sum is 3 + 7 = 10
, which are not adjacent in the array.
Let’s proceed with the following assumptions until clarified:
O(n^2)
time complexity.nums
array.import java.util.*;
public class MaxPairSum {
public static int maxPairSum(int[] nums) {
List<int[]> numIdxList = new ArrayList<>();
// Create list of (value, index) pairs
for (int i = 0; i < nums.length; i++) {
numIdxList.add(new int[]{nums[i], i});
}
// Sort the list based on the values in descending order
numIdxList.sort((a, b) -> Integer.compare(b[0], a[0]));
// Find two non-adjacent maximum values
for (int i = 0; i < numIdxList.size(); i++) {
for (int j = i + 1; j < numIdxList.size(); j++) {
int[] first = numIdxList.get(i);
int[] second = numIdxList.get(j);
if (Math.abs(first[1] - second[1]) > 1) {
return first[0] + second[0];
}
}
}
// It should always be possible to find two non-adjacent values in a valid input array
return -1; // Indicate error in unexpected cases, but we assume input validity
}
public static void main(String[] args) {
int[] nums = {3, 5, 2, 3, 7, 1};
System.out.println(maxPairSum(nums)); // Output: 10
}
}
O(n log n)
, where n
is the length of the input array.O(n^2)
in the nested loop to find non-adjacent pairs.
This solution should work efficiently for moderately large arrays. Further optimization, if needed, can potentially be done by exploring advanced data structures or algorithmic tweaks based on specific array properties provided in the problem statement.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?