当前位置:网站首页>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;}}
边栏推荐
猜你喜欢

CobalStrike(CS)基础超级详细版

社交电商:流量红利已尽,裂变营销是最低成本的获客之道

shell脚本循环语句

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

【HMS core】【Ads Kit】华为广告——海外应用在国内测试正式广告无法展示

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

Interface Test Framework Practice | Process Encapsulation and Test Case Design Based on Encrypted Interface

Kotlin-Flow常用封装类:StateFlow的使用

常见荧光染料修饰多种基团及其激发和发射波长数据一览数据

MOSN 反向通道详解
随机推荐
【Harmony OS】【ARK UI】ets use startAbility or startAbilityForResult to invoke Ability
【Harmony OS】【FAQ】Hongmeng Questions Collection 1
Coordinate knowledge in digital twin campus scenarios
【HMS core】【Ads Kit】华为广告——海外应用在国内测试正式广告无法展示
2022/08/02 学习笔记 (day22) 多线程
c语言结构体中的冒泡排序
打破传统电商格局,新型社交电商到底有什么优点?
如何利用 Flutter 实现炫酷的 3D 卡片和帅气的 360° 展示效果
Common fluorescent dyes to modify a variety of groups and its excitation and emission wavelength data in the data
接口测试框架实战(二)| 接口请求断言
Secondary development of WinForm controls
Shell conditional statement judgment
User password verification
刚上线就狂吸70W粉,新型商业模式“分享购”来了,你知道吗?
【Harmony OS】【ArkUI】ets开发 基础页面布局与数据连接
Fluorescent marker peptides FITC/AMC/FAM/Rhodamine TAMRA/Cy3 / Cy5 / Cy7 - Peptide
阿里云对象存储oss私有桶生成链接
获取Ip工具类
在树莓派上搭建属于自己的网页(1)
[Harmony OS] [ARK UI] ETS context basic operations