LeetCode 题解工作台
数位和相等数对的最大和
给你一个下标从 0 开始的数组 nums ,数组中的元素都是 正 整数。请你选出两个下标 i 和 j ( i != j ),且 nums[i] 的数位和 与 nums[j] 的数位和相等。 请你找出所有满足条件的下标 i 和 j ,找出并返回 nums[i] + nums[j] 可以得到的 最大值 …
4
题型
6
代码语言
3
相关题
当前训练重点
中等 · 数组·哈希·扫描
答案摘要
我们可以用一个哈希表 记录每个数位和对应的最大值,初始化一个答案变量 $ans = -1$。 接下来,我们遍历数组 ,对于每个数 ,我们计算它的数位和 ,如果 在哈希表 中存在,那么我们就更新答案 $ans = \max(ans, d[x] + v)$。然后更新哈希表 $d[x] = \max(d[x], v)$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个下标从 0 开始的数组 nums ,数组中的元素都是 正 整数。请你选出两个下标 i 和 j(i != j),且 nums[i] 的数位和 与 nums[j] 的数位和相等。
请你找出所有满足条件的下标 i 和 j ,找出并返回 nums[i] + nums[j] 可以得到的 最大值。如果不存在这样的下标对,返回 -1。
示例 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 <= 1051 <= nums[i] <= 109
解题思路
方法一:哈希表
我们可以用一个哈希表 记录每个数位和对应的最大值,初始化一个答案变量 。
接下来,我们遍历数组 ,对于每个数 ,我们计算它的数位和 ,如果 在哈希表 中存在,那么我们就更新答案 。然后更新哈希表 。
最后返回答案 即可。
由于 中的元素最大为 ,因此数位和最大为 ,我们可以直接定义一个长度为 的数组 来代替哈希表。
时间复杂度 ,空间复杂度 ,其中 是数组 的长度,而 和 分别是数组 中的元素的最大值和数位和的最大值。本题中 ,。
class Solution:
def maximumSum(self, nums: List[int]) -> int:
d = defaultdict(int)
ans = -1
for v in nums:
x, y = 0, v
while y:
x += y % 10
y //= 10
if x in d:
ans = max(ans, d[x] + v)
d[x] = max(d[x], v)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n \log m) |
| 空间 | O(\log m) |
面试官常问的追问
外企场景- question_mark
Candidate understands the importance of efficient hashing.
- question_mark
Candidate is familiar with digit manipulation and sum of digits calculation.
- question_mark
Candidate recognizes the challenge of balancing time complexity with correctness.
常见陷阱
外企场景- error
Not efficiently updating the hash table, leading to unnecessary re-checks.
- error
Overlooking edge cases where no valid pairs exist, returning the correct -1 value.
- error
Misunderstanding the sum of digits calculation and applying it incorrectly.
进阶变体
外企场景- arrow_right_alt
What happens if the array only has one number?
- arrow_right_alt
How does the solution handle very large numbers or arrays at the upper constraint limits?
- arrow_right_alt
Can we optimize this further if there are only a few numbers with unique digit sums?