当前位置:网站首页>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;}}
边栏推荐
- shell script loop statement
- Interface test framework combat (1) | Requests and interface request construction
- typescript49-交叉类型
- 社交电商如何做粉丝运营?云平台怎么选择商业模式?
- 【Harmony OS】【ARK UI】ets use startAbility or startAbilityForResult to invoke Ability
- MySQL 出现 The table is full 的解决方法
- DFS's complement to pruning
- MOSN 反向通道详解
- GIS数据漫谈(五)— 地理坐标系统
- typescript47-函数之间的类型兼容性
猜你喜欢

接口测试如何准备测试数据

普乐蛙VR台风体验馆厂家VR防震减灾模拟VR沉浸式体验设备

测试人员的价值体现在哪里

探索性测试的概念及方法

【Harmony OS】【ARK UI】Date 基本操作

【Biotin Azide|cas:908007-17-0】Price_Manufacturer

unity2D横板游戏教程6-敌人AI以及受击动画

接口和协议

Peptides mediated PEG DSPE of phospholipids, targeted functional materials - PEG - RGD/TAT/NGR/APRPG

安装IIS服务(Internet信息服务(Internet Information Services,简写IIS,互联网信息服务)
随机推荐
Where is the value of testers
User password verification
shell脚本循环语句
MySQL 删除表数据,重置自增 id 为 0 的两个方式
刚上线就狂吸70W粉,新型商业模式“分享购”来了,你知道吗?
tag单调栈-单调栈预备知识-lt.739. 每日温度
Talking about GIS Data (6) - Projected Coordinate System
【Harmony OS】【ArkUI】ets开发 基础页面布局与数据连接
传统企业如何转型社交电商,泰山众筹的玩法有哪些?
Alienware上线首个数字时装AR试穿体验
Bubble sort in c language structure
【Harmony OS】【FAQ】鸿蒙问题合集1
js garbage collection mechanism
Interface Test Framework Practice | Process Encapsulation and Test Case Design Based on Encrypted Interface
idea使用@Autowired注解爆红原因及解决方法
接口测试 Mock 实战(二) | 结合 jq 完成批量化的手工 Mock
数字孪生园区场景中的坐标知识
获取Ip工具类
社交电商如何做粉丝运营?云平台怎么选择商业模式?
Shell条件语句判断