Similar Problems

Similar Problems not available

Minimize Maximum Pair Sum In Array - Leetcode Solution

Companies:

  • amazon

LeetCode:  Minimize Maximum Pair Sum In Array Leetcode Solution

Difficulty: Medium

Topics: greedy sorting array two-pointers  

Problem Statement: Given an array nums of n integers, find the maximum value of a pair (nums[i], nums[j]) such that i != j.

Return the minimum possible value of any pair sum.

Input: nums = [3,5,2,3] Output: 7 Explanation: The optimal choice of pair is (5,2) with a pair sum of 7.

Approach: The problem can be solved using binary search with a lower bound of 0 and an upper bound of max(nums). The target value for binary search is the mid value of the lower bound and upper bound. If the pair sum is greater than or equal to the target value, then the mid value can be used as the lower bound for the next iteration. Otherwise, the mid value can be used as the upper bound for the next iteration. Finally, the minimum value of pair sum can be returned as the result.

Algorithm:

  1. Initialize variables lo as 0 and hi as the maximum value in the given array nums.
  2. While lo <= hi, do the following: a. Initialize mid as (lo+hi)/2. b. Initialize flag as False. c. Traverse through the array and for each element x, do the following: i. Traverse through the array again and for each element y, do the following: (a) If x+y >= mid and x != y, then set flag as True and break the inner loop. d. If flag is True, then set lo as mid+1. Otherwise, set hi as mid-1.
  3. Return lo as the final answer.

Code:

class Solution: def minPairSum(self, nums: List[int]) -> int: n = len(nums) lo, hi = 0, max(nums) res = 0 while lo <= hi: mid = (lo + hi) // 2 flag = False for i in range(n): for j in range(n): if i != j and nums[i] + nums[j] >= mid: flag = True break if flag: break if flag: res = mid lo = mid + 1 else: hi = mid - 1 return res

Time Complexity: O(n log m), where n is the length of the input array and m is the maximum value in the given array. Space Complexity: O(1)

Minimize Maximum Pair Sum In Array Solution Code

1