当前位置:网站首页>力扣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;
}
}

边栏推荐
- User password encryption tool
- Detailed explanation of MOSN reverse channel
- 社交电商如何做粉丝运营?云平台怎么选择商业模式?
- 接口测试如何准备测试数据
- IO process thread -> thread -> day5
- 【Harmony OS】【FAQ】Hongmeng Questions Collection 1
- Kotlin-Flow common encapsulation class: the use of StateFlow
- 数字孪生园区场景中的坐标知识
- js garbage collection mechanism
- Interface test practice | Detailed explanation of the difference between GET / POST requests
猜你喜欢

typescript41-class类的私有修饰符

WinForm的控件二次开发

Online password generator tool recommendation

社交电商:链动2+1模式,为什么能在电商行业生存那么久?

Tributyl-mercaptophosphane "tBuBrettPhos Pd(allyl)" OTf), 1798782-17-8

DFS对剪枝的补充

Jmeter 模拟多用户登录的两种方法

How to use the interface management tool YApi?Beautiful, easy to manage, super easy to use

社交电商如何做粉丝运营?云平台怎么选择商业模式?

typescript46-函数之间的类型兼容性
随机推荐
Interface testing framework of actual combat (2) | interface request assertion
Talking about GIS Data (6) - Projected Coordinate System
【Harmony OS】【ArkUI】ets开发 图形与动画绘制
Super handy drawing tool is recommended
typescript42-readonly修饰符
2022 Henan Mengxin League Game (4): Zhengzhou University of Light Industry E - Sleep Well
typescript45-接口之间的兼容性
[Harmony OS] [ArkUI] ets development graphics and animation drawing
多肽介导PEG磷脂——靶向功能材料之DSPE-PEG-RGD/TAT/NGR/APRPG
Online password generator tool recommendation
【Harmony OS】【ARK UI】Date 基本操作
Interface test framework combat (1) | Requests and interface request construction
Apache DolphinScheduler版本2.0.5分布式集群的安装
【Harmony OS】【ARK UI】ETS 上下文基本操作
typescript39-class类的可见修饰符
三丁基-巯基膦烷「tBuBrettPhos Pd(allyl)」OTf),1798782-17-8
Harmony OS ets ArkUI 】 【 】 the development basic page layout and data connection
StarRocks July Community Update
7.Keras开发简介
数据库基本概述与SQL概述