Leetcode 2974. Minimum Number Game
You are given an integer array nums
consisting of 2 * n integers. You need to divide these integers into exactly n pairs such that the maximum minimum pair sum is minimized. A pair sum is defined as the sum of a number from the left half of the list and a number from the right half of the list, where the left half consists of the first n integers and the right half consists of the last n integers.
Return the minimized maximum pair sum.
nums
will always have an even number of elements with the given constraints 2 <= 2 * n <= 10^5
.nums
are between 1
and 10^6
.To minimize the maximum pair sum, a good approach is:
[a1, a2, ..., an, b1, b2, ..., bn]
, pair ai
with bn-i+1
for 1 <= i <= n
.Here is the C++ implementation of the above strategy:
#include <iostream>
#include <vector>
#include <algorithm>
int minimizeMaximumPairSum(std::vector<int>& nums) {
// Sort the array
std::sort(nums.begin(), nums.end());
int n = nums.size() / 2;
int max_pair_sum = 0;
for (int i = 0; i < n; ++i) {
// Calculate the pair sum
int pair_sum = nums[i] + nums[nums.size() - 1 - i];
// Update the maximum pair sum
max_pair_sum = std::max(max_pair_sum, pair_sum);
}
return max_pair_sum;
}
int main() {
std::vector<int> nums = {3, 5, 2, 3, 8, 7, 4, 6};
std::cout << "Minimized Maximum Pair Sum is: " << minimizeMaximumPairSum(nums) << std::endl;
return 0;
}
Thus, the overall time complexity is (O(n \log n)).
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?