当前位置:网站首页>力扣561. 数组拆分
力扣561. 数组拆分
2022-08-03 04:56:00 【洋圏外の彼女】
给定长度为 2n 的整数数组 nums ,你的任务是将这些数分成 n 对, 例如 (a1, b1), (a2, b2), …, (an, bn) ,使得从 1 到 n 的 min(ai, bi) 总和最大。
返回该 最大总和 。
示例 1:
输入:nums = [1,4,3,2]
输出:4
解释:所有可能的分法(忽略元素顺序)为:
- (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3
- (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3
- (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4 所以最大总和为 4
示例 2:
输入:nums = [6,2,6,5,1,2]
输出:9
解释:最优的分法为 (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/array-partition
对于nums数组拆分的n对[a,b]数组中,选择a,b之间小的一个数字,相加得到一个最大的总和
第一个示例我们可以看出,是可以先将nums数组进行排序
我们将nums数组分为了(nums[0],nums[1]) = (1,2);
(nums[2],nums[3]) = (3,4)
两对,并且选择了1+3的带最大的总和;
也就是nums[0]+nums[2];
第二个示例,也可以先将数组进行排序[1,2,2,5,6,6]
而最大的总和是nums[0]+nums[2]+nums[4] = 1+2+6=9
代码
class Solution {
public int arrayPairSum(int[] nums) {
Arrays.sort(nums);
int sum = 0;
//从第一个开始,每隔一个在加
for(int i=0;i<nums.length;i=i+2){
sum = sum +nums[i];
}
return sum;
}
}

边栏推荐
- BIOTIN ALKYNE CAS:773888-45-2价格,供应商
- Where is the value of testers
- 【生物素叠氮化物|cas:908007-17-0】价格_厂家
- Redis连接不上的报错解决方案汇总
- CobalStrike(CS)基础超级详细版
- Interface Test Framework Practice (4) | Get Schema Assertion
- 接口测试实战| GET/POST 请求区别详解
- shell script loop statement
- 建立树形结构
- Common lipophilic cell membrane dyes DiO, Dil, DiR, Did spectrograms and experimental procedures
猜你喜欢

Modified BiotinDIAZO-Biotin-PEG3-DBCO|diazo-biotin-tripolyethylene glycol-diphenylcyclooctyne

2022/08/02 Study Notes (day22) Multithreading

超好用的画图工具推荐

Interface Test Framework Practice | Process Encapsulation and Test Case Design Based on Encrypted Interface

idea使用@Autowired注解爆红原因及解决方法

Windows 安装PostgreSQL

redis键值出现 xacxedx00x05tx00&的解决方法

私域流量引流方法?分享购火爆的商业模式,你值得拥有

IO进程线程->线程->day5

Talking about GIS Data (6) - Projected Coordinate System
随机推荐
接口和抽象
typescript49-交叉类型
Windows 安装PostgreSQL
软件开发的最大的区别是什么?
探索性测试的概念及方法
Two ways to simulate multi-user login in Jmeter
BIOTIN ALKYNE CAS:773888-45-2价格,供应商
普乐蛙VR台风体验馆厂家VR防震减灾模拟VR沉浸式体验设备
【HMS core】【Ads Kit】Huawei Advertising——Overseas applications are tested in China. Official advertisements cannot be displayed
内部类、static关键字、final
OSI的分层特点、传输过程与三次握手、四次挥手、tcp与udp包头的描述
2022暑假牛客多校联赛第一场
How to use the interface management tool YApi?Beautiful, easy to manage, super easy to use
接口测试框架实战 | 流程封装与基于加密接口的测试用例设计
建立树形结构
2022/08/02 Study Notes (day22) Multithreading
Interface testing framework combat (3) | JSON request and response assertion
Kotlin-Flow常用封装类:StateFlow的使用
【Harmony OS】【FAQ】鸿蒙问题合集1
Bubble sort in c language structure