当前位置:网站首页>Power button 561. An array of split
Power button 561. An array of split
2022-08-03 05:11:00 【The other girl outside the world】
Given an integer array nums of length 2n, your task is to divide these numbers into n pairs, eg (a1, b1), (a2, b2), …, (an, bn) such that from 1 to nThe sum of min(ai, bi) is max.
Returns the max sum .
Example 1:
Input: nums = [1,4,3,2]
Output: 4
Explanation: All possibleThe division method (ignoring the order of elements) is:
- (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 so the maximum sum is 4
Example 2:
Input: nums = [6,2,6,5,1,2]
Output: 9
Explanation: The optimal division method is (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2+ 6 = 9
Source: LeetCode
Link: https://leetcode.cn/problems/array-partition
In the n pairs of [a, b] arrays split by the nums array, select a smaller number between a and b, and add them to get a maximum sum
We can see from the first example that isYou can sort the nums array first
We divide the nums array into (nums[0],nums[1]) = (1,2);
(nums[2],nums[3]) = (3,4)
Two pairs, and the largest sum of 1+3 is selected;
That is, nums[0]+nums[2];
In the second example, you can also put the array firstsort [1,2,2,5,6,6]
and the largest sum is nums[0]+nums[2]+nums[4] = 1+2+6=9
Code
class Solution {public int arrayPairSum(int[] nums) {Arrays.sort(nums);int sum = 0;//Start from the first one, add every other for(int i=0;i<nums.length;i=i+2){sum = sum +nums[i];}return sum;}}
边栏推荐
- 普乐蛙VR台风体验馆厂家VR防震减灾模拟VR沉浸式体验设备
- Modified BiotinDIAZO-Biotin-PEG3-DBCO|diazo-biotin-tripolyethylene glycol-diphenylcyclooctyne
- typescript43-类型兼容性说明
- typescript40-class类的保护修饰符
- Interface Test Framework Practice (4) | Get Schema Assertion
- [Harmony OS] [ARK UI] ETS context basic operations
- RequestContextHolder
- 【Harmony OS】【FAQ】Hongmeng Questions Collection 1
- Where is the value of testers
- 常见荧光染料修饰多种基团及其激发和发射波长数据一览数据
猜你喜欢
三丁基-巯基膦烷「tBuBrettPhos Pd(allyl)」OTf),1798782-17-8
刚上线就狂吸70W粉,新型商业模式“分享购”来了,你知道吗?
力扣561. 数组拆分
WinForm的控件二次开发
「短视频+社交电商」营销模式爆发式发展,带来的好处有什么?
测试人员的价值体现在哪里
超好用的画图工具推荐
【Harmony OS】【FAQ】Hongmeng Questions Collection 1
安装IIS服务(Internet信息服务(Internet Information Services,简写IIS,互联网信息服务)
设计模式——组合模式、享元模式(Integer缓存)(结构型模式)
随机推荐
【精讲】利用原生js实现todolist
探索性测试的概念及方法
shell脚本循环语句
DDL操作数据库、表、列
mysql 创建索引的三种方式
用户密码验证
Jmeter 模拟多用户登录的两种方法
在线密码生成工具推荐
idea使用@Autowired注解爆红原因及解决方法
Flink状态
【Harmony OS】【FAQ】鸿蒙问题合集1
Create a tree structure
【生物素叠氮化物|cas:908007-17-0】价格_厂家
在竞争白热化的电商行业,链动2+1为什么还有企业在用
社交电商如何做粉丝运营?云平台怎么选择商业模式?
接口管理工具YApi怎么用?颜值高、易管理、超好用
MCM箱模型建模方法及大气O3来源解析
高可用 两地三中心
MySQL 删除表数据,重置自增 id 为 0 的两个方式
接口和抽象