561. Array Partition I

题目链接

561. Array Partition I

题目分析

本题给了一个数组,要求将数组分为n个只有2个元素的一对。
使得每对数字中最小的数加起来的和最大。

思路

首先,需要把数组分为2个一对。用array_chunk即可。

其次,需要取每对数字中最小的那一个数字,用于求和。
因为我们需要最终求和最大,但每组数字中又取最小。
因此,要使每组中最大的数字和最小的数组之差最小,这样才能使“损失”最小。

例如,[1,2,7,8]

若分为[[1,8],[2,7]][[1,7],[2,8]]两组,那么每组取最小后,会得到[1,2]。求和后为3。
当比较大的数字和比较小的数字数字组成一对时,较大的数字都没办法用于求和(因为题目要取每组数字中最小的数)。
当分为[[1,2],[7,8]]两组时,每组取最小后,会得到[1,7]。求和后为8,比3大。

故,先对数组排序,再两两分组,从每组中获取第0个元素参与计算即可。

最终代码

<?php
class Solution {function arrayPairSum($nums) {sort($nums);$a = array_chunk($nums,2);return array_sum(array_column($a,0));}
}
复制代码

若觉得本文章对你有用,欢迎用爱发电资助。

Leetcode PHP题解--D14 561. Array Partition I相关推荐

  1. [LeetCode]561. Array Partition I (数组分区 1)

    561. Array Partition I Given an array of 2n integers, your task is to group these integers into n pa ...

  2. Leetcode刷题记录[java]——561 Array Partition I

    一.前言 二.题561 Array Partition I Given an array of 2n integers, your task is to group these integers in ...

  3. 561.Array Partition I--Python

    刚开始学习Python编程,欢迎交流学习! 561.Array Partition I Given an array of 2n integers, your task is to group the ...

  4. 【刷leetcode,拿Offer-009】561. Array Partition I(贪心,C++)

    题目链接 Given an array of 2n integers, your task is to group these integers into n pairs of integer, sa ...

  5. LeetCode 561. Array Partition I

    题目: Given an array of 2n integers, your task is to group these integers into n pairs of integer, say ...

  6. LeetCode 561 Array Partition I(数组划分)

    翻译 原文 Given an array of 2n integers, your task is to group these integers into n pairs of integer, s ...

  7. leetcode#561 Array Partition I

    Description: Given an array of 2n integers, your task is to group these integers into n pairs of int ...

  8. 561. Array Partition I

    原题 Given an array of 2n integers, your task is to group these integers into n pairs of integer, say ...

  9. 561. 数组拆分 I(javascript)561. Array Partition I

    给定长度为 2n 的整数数组 nums ,你的任务是将这些数分成 n 对, 例如 (a1, b1), (a2, b2), -, (an, bn) ,使得从 1 到 n 的 min(ai, bi) 总和 ...

最新文章

  1. 专为设计师而写的GitHub快速入门教程
  2. axios delete有请求体吗_封装 axios 取消重复请求
  3. python右对齐输出如果结果超过30个字符_Python3 输出字符串左对齐、右对齐、居中对齐...
  4. 你有一份云栖大会的IoT邀请函,请查收
  5. windows下搭建基于nginx的rtmp服务器
  6. PAT乙级(Basic Level)真题--跟奥巴马一起编程(15)
  7. zabbix mysql.status_zabbix 监控mysql状态
  8. 谈MicroMessageTest的开始创建
  9. Java并行计算线程池_干货!线程池+CountDownLatch,实现 多线程并发计算、汇总
  10. 兔子问题JAVA编程题
  11. Spark1.5.1学习笔记汇总
  12. Flutter 的ButtonBar
  13. ORL Face94 LFW
  14. 最有用的25个 Matplotlib图(含Python代码模板)
  15. 个人计算机软件著作权,个人可以申请软件专利权吗?软件著作权申请的注意事项有哪些?...
  16. 杭州电子科技大学java刷题_杭州电子科技大学的OJ
  17. 百度地图和百度导航冲突问题
  18. java wgs84 百度坐标_javascript 实现wgs84 坐标转百度坐标
  19. 如何用Excel做动态图表
  20. 提示用户输入一个高考_高考报名用户名密码显示错误怎么办

热门文章

  1. 5G最完整的PPT教材
  2. 机器学习中的数学基础(2)——理解基、线性组合与向量空间
  3. 知乎李大海:AI 不只是噱头,满足需求才是真落地
  4. Python 之 matplotlib (十)Image
  5. 物理理论发展放缓?这是一种认知误判
  6. BERT为什么是NLP的革新者
  7. 空地通信传输详解——飞机是这样和地面通信的
  8. 潘云鹤院士:AI2.0和工业经济发展智能化
  9. 颠覆性技术的兴起及其影响
  10. Science:人工智能的发展离不开神经科学,先天结构或是下一个方向