当前位置:网站首页>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;}}
边栏推荐
- typescript43-类型兼容性说明
- 社交电商:链动2+1模式,为什么能在电商行业生存那么久?
- 三丁基-巯基膦烷「tBuBrettPhos Pd(allyl)」OTf),1798782-17-8
- Secondary development of WinForm controls
- 【Harmony OS】【ARK UI】Date 基本操作
- Kotlin-Flow常用封装类:StateFlow的使用
- IO进程线程->线程->day5
- 【Harmony OS】【ArkUI】ets开发 基础页面布局与数据连接
- Practical application of WebSocket
- Online password generator tool recommendation
猜你喜欢

GIS数据漫谈(五)— 地理坐标系统

【HMS core】【Ads Kit】Huawei Advertising——Overseas applications are tested in China. Official advertisements cannot be displayed

高可用 两地三中心

打破传统电商格局,新型社交电商到底有什么优点?

DFS's complement to pruning

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

Shell conditional statement judgment

荧光标记多肽FITC/AMC/FAM/Rhodamine/TAMRA/Cy3/Cy5/Cy7-Peptide

在竞争白热化的电商行业,链动2+1为什么还有企业在用

数字化时代,企业如何建立自身的云平台与商业模式的选择?
随机推荐
移动流量的爆发式增长,社交电商如何选择商业模式
Coordinate knowledge in digital twin campus scenarios
社交电商:流量红利已尽,裂变营销是最低成本的获客之道
typescript45-接口之间的兼容性
WebSocket的实际应用
【Harmony OS】【ArkUI】ets开发 基础页面布局与数据连接
OSI的分层特点、传输过程与三次握手、四次挥手、tcp与udp包头的描述
MySql 创建索引
如何利用 Flutter 实现炫酷的 3D 卡片和帅气的 360° 展示效果
技术分享 | 接口自动化测试中如何对xml 格式做断言验证?
BIOTIN ALKYNE CAS:773888-45-2价格,供应商
接口测试框架实战(三)| JSON 请求与响应断言
Where is the value of testers
c语言结构体中的冒泡排序
1.一个神经网络示例
2022暑假牛客多校联赛第一场
typescript41-class类的私有修饰符
接口测试框架实战(二)| 接口请求断言
Windows 安装PostgreSQL
IO进程线程->线程->day5