zoukankan      html  css  js  c++  java
  • [LeetCode] 1877. Minimize Maximum Pair Sum in Array

    The pair sum of a pair (a,b) is equal to a + b. The maximum pair sum is the largest pair sum in a list of pairs.

    • For example, if we have pairs (1,5)(2,3), and (4,4), the maximum pair sum would be max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8.

    Given an array nums of even length n, pair up the elements of nums into n / 2 pairs such that:

    • Each element of nums is in exactly one pair, and
    • The maximum pair sum is minimized.

    Return the minimized maximum pair sum after optimally pairing up the elements.

    Example 1:

    Input: nums = [3,5,2,3]
    Output: 7
    Explanation: The elements can be paired up into pairs (3,3) and (5,2).
    The maximum pair sum is max(3+3, 5+2) = max(6, 7) = 7.
    

    Example 2:

    Input: nums = [3,5,4,2,4,6]
    Output: 8
    Explanation: The elements can be paired up into pairs (3,5), (4,4), and (6,2).
    The maximum pair sum is max(3+5, 4+4, 6+2) = max(8, 8, 8) = 8.

    Constraints:

    • n == nums.length
    • 2 <= n <= 105
    • n is even.
    • 1 <= nums[i] <= 105

    数组中最大数对和的最小值。

    一个数对 (a,b) 的 数对和 等于 a + b 。最大数对和 是一个数对数组中最大的 数对和 。

    比方说,如果我们有数对 (1,5) ,(2,3) 和 (4,4),最大数对和 为 max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8 。
    给你一个长度为 偶数 n 的数组 nums ,请你将 nums 中的元素分成 n / 2 个数对,使得:

    nums 中每个元素 恰好 在 一个 数对中,且
    最大数对和 的值 最小 。
    请你在最优数对划分的方案下,返回最小的 最大数对和 。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/minimize-maximum-pair-sum-in-array
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    思路是逼近型的 two pointer。题目给的是一个长度为偶数 n 的数组,你需要把数组分成若干个 pair。注意观察题目中的例子我们可以发现,每个 pair 都会产生一个数字 max,是每两个数字之间较大的那一个。这样 n / 2 个 pair 会产生 n / 2 个 max。我们要再返回这 n / 2 个 max 中最大的那个数字,但是需要让这个最大的数字尽可能小。

    所以思路倒推回去就是

    1. 我们需要使得每一个 pair 产生的 max 尽可能地小
    2. 这样才能使得 max 尽可能地小
    3. 同时最后要找的数字也是最小的

    对于 step1,为了让 pair 尽可能小,我们需要对 input 数组排序,然后让最大的数字跟最小的数字 pair,这样每个 pair 生成的较大数字才会比较小,同时也会导致全局的 max 是最小的。

    时间O(nlogn) - sort

    空间O(1)

    Java实现

     1 class Solution {
     2     public int minPairSum(int[] nums) {
     3         Arrays.sort(nums);
     4         int max = Integer.MIN_VALUE;
     5         int res = Integer.MAX_VALUE;
     6         int left = 0;
     7         int right = nums.length - 1;
     8         while (left < right) {
     9             int i = nums[left];
    10             int j = nums[right];
    11             max = Math.max(max, i + j);
    12             left++;
    13             right--;
    14         }
    15         return max;
    16     }
    17 }

    LeetCode 题目总结

  • 相关阅读:
    Account group in ERP and its mapping relationship with CRM partner group
    错误消息Number not in interval XXX when downloading
    错误消息Form of address 0001 not designated for organization
    Algorithm类介绍(core)
    梯度下降与随机梯度下降
    反思
    绘图: matplotlib核心剖析
    ORB
    SIFT
    Harris角点
  • 原文地址:https://www.cnblogs.com/cnoodle/p/14877074.html
Copyright © 2011-2022 走看看