当前位置:网站首页>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;}}
边栏推荐
- 【Harmony OS】【FAQ】鸿蒙问题合集1
- 内部类、static关键字、final
- js garbage collection mechanism
- typescript45-接口之间的兼容性
- MOSN 反向通道详解
- Practical application of WebSocket
- Interface testing framework of actual combat (2) | interface request assertion
- 自组织是管理者和成员的双向奔赴
- unity2D横板游戏教程6-敌人AI以及受击动画
- Coordinate knowledge in digital twin campus scenarios
猜你喜欢
随机推荐
[Fine talk] Using native js to implement todolist
超好用的画图工具推荐
presto安装部署教程
自组织是管理者和成员的双向奔赴
User password verification
如何利用 Flutter 实现炫酷的 3D 卡片和帅气的 360° 展示效果
常见亲脂性细胞膜染料DiO, Dil, DiR, Did光谱图和实验操作流程
closures in js
UV decomposition of biotin - PEG2 - azide | CAS: 1192802-98-4 biotin connectors
数据库基本概述与SQL概述
Get the Ip tool class
Flink状态
typescript47-函数之间的类型兼容性
User password encryption tool
C#异步和多线程
typescript43-类型兼容性说明
三丁基-巯基膦烷「tBuBrettPhos Pd(allyl)」OTf),1798782-17-8
Secondary development of WinForm controls
13.< tag-动态规划和回文字串>lt.647. 回文子串 + lt.516.最长回文子序列
GIS数据漫谈(五)— 地理坐标系统