当前位置:网站首页>LeetCode 2342. 数位和相等数对的最大和
LeetCode 2342. 数位和相等数对的最大和
2022-07-30 01:23:00 【Michael阿明】
1. 题目
给你一个下标从 0 开始的数组 nums ,数组中的元素都是 正 整数。请你选出两个下标 i 和 j(i != j)
,且 nums[i]
的数位和 与 nums[j]
的数位和相等。
请你找出所有满足条件的下标 i 和 j ,找出并返回 nums[i] + nums[j]
可以得到的 最大值 。
示例 1:
输入:nums = [18,43,36,13,7]
输出:54
解释:满足条件的数对 (i, j) 为:
- (0, 2) ,两个数字的数位和都是 9 ,相加得到 18 + 36 = 54 。
- (1, 4) ,两个数字的数位和都是 7 ,相加得到 43 + 7 = 50 。
所以可以获得的最大和是 54 。
示例 2:
输入:nums = [10,12,19,14]
输出:-1
解释:不存在满足条件的数对,返回 -1 。
提示:
1 <= nums.length <= 10^5
1 <= nums[i] <= 10^9
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/max-sum-of-a-pair-with-equal-sum-of-digits
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 解题
- 和作为 key,值为数字的 list,之后对 list 排序,取最大的2个
class Solution:
def maximumSum(self, nums: List[int]) -> int:
def bitsum(x):
s = 0
while x:
s += x%10
x //= 10
return s
d = defaultdict(list)
for x in nums:
d[bitsum(x)].append(x)
ans = -1
for k, v in d.items():
if len(v) > 1:
v.sort()
ans = max(ans, sum(v[-2:]))
return ans
384 ms 27.4 MB Python3
- 排序,可以改为只保留最大的两个
class Solution:
def maximumSum(self, nums: List[int]) -> int:
def bitsum(x):
s = 0
while x:
s += x%10
x //= 10
return s
d = defaultdict(list)
for x in nums:
s = bitsum(x)
if len(d[s]) <= 1:
d[s].append(x)
else:
arr = d[s]
if arr[0] > arr[1]:
arr[0], arr[1] = arr[1], arr[0]
if x > arr[0]:
d[s] = [x, arr[1]]
ans = -1
for k, v in d.items():
if len(v) > 1:
ans = max(ans, sum(v))
return ans
372 ms 26.5 MB Python3
我的CSDN博客地址 https://michael.blog.csdn.net/
长按或扫码关注我的公众号(Michael阿明),一起加油、一起学习进步!
边栏推荐
猜你喜欢
随机推荐
裁员趋势下的大厂面试:“字节跳动”
Recommendation systems: feature engineering, common features
jar包解压后再打包为jar
Detailed explanation of nacos cluster configuration
Graph Theory: Bipartite Graphs
Minimum number to rotate array
机械设备制造企业如何借助ERP系统,解决成本核算难题?
CMake Tutorial 巡礼(0)_总述
Navicat如何连接MySQL
【MySQL系列】MySQL数据库基础
SSM整合案例
CMake Tutorial 巡礼(1)_基础的起点
Replace the executable file glibc version of the one
【Flutter】混合开发之Flutter预加载解决第一次加载页面缓慢问题
自学HarmonyOS应用开发(53)- 获取当前位置
十一、uni-app生成弹窗及换行
【Incubator DAY18】Interesting exchange【Simulation】【Math】
Finding a 2D Array
接口测试自动化后起之秀-YApi接口管理平台
Internship in a group