zoukankan      html  css  js  c++  java
  • b_lc_数组中最大数对和的最小值(排序+思维 | 进阶:第k)

    给你一个长度为 偶数 n 的数组 nums ,请你将 nums 中的元素分成 n / 2 个数对,使得:

    • nums 中每个元素 恰好 在 一个 数对中,且
    • 最大数对和 的值 最小 。

    请你在最优数对划分的方案下,返回最小的 最大数对和 。

    示例 1:
    输入:nums = [3,5,2,3]
    输出:7
    解释:数组中的元素可以分为数对 (3,3) 和 (5,2) 。
    最大数对和为 max(3+3, 5+2) = max(6, 7) = 7 。

    思路:对于 1,2,3,4,5,6 这个公差 d=1 例子,如果不按照 [头-尾] 取,就得不到最大值最小。这个性质可以扩展到公差 d>1 的有序序列

    class Solution:
        def minPairSum(self, nums: List[int]) -> int:
            n = len(nums)
            nums = sorted(nums)
            ans = 0
            for i in range(int(n/2)):
                ans = max(ans, nums[i] + nums[n-i-1])
            return ans
    

    进阶:https://atcoder.jp/contests/arc121/tasks/arc121_d

  • 相关阅读:
    Shell Sort
    Insertion Sort
    Notations
    Nakamori Akina
    QuickSort
    Onedrive File Open Problem
    JSON Introduction
    System Call
    进程软中断通信
    Bubble Sort
  • 原文地址:https://www.cnblogs.com/wdt1/p/14835804.html
Copyright © 2011-2022 走看看