LeetCode 题解工作台

数位和相等数对的最大和

给你一个下标从 0 开始的数组 nums ,数组中的元素都是 正 整数。请你选出两个下标 i 和 j ( i != j ),且 nums[i] 的数位和 与 nums[j] 的数位和相等。 请你找出所有满足条件的下标 i 和 j ,找出并返回 nums[i] + nums[j] 可以得到的 最大值 …

category

4

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·哈希·扫描

bolt

答案摘要

我们可以用一个哈希表 记录每个数位和对应的最大值,初始化一个答案变量 $ans = -1$。 接下来,我们遍历数组 ,对于每个数 ,我们计算它的数位和 ,如果 在哈希表 中存在,那么我们就更新答案 $ans = \max(ans, d[x] + v)$。然后更新哈希表 $d[x] = \max(d[x], v)$。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个下标从 0 开始的数组 nums ,数组中的元素都是 整数。请你选出两个下标 iji != j),且 nums[i] 的数位和 与  nums[j] 的数位和相等。

请你找出所有满足条件的下标 ij ,找出并返回 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 <= 105
  • 1 <= nums[i] <= 109
lightbulb

解题思路

方法一:哈希表

我们可以用一个哈希表 dd 记录每个数位和对应的最大值,初始化一个答案变量 ans=1ans = -1

接下来,我们遍历数组 numsnums,对于每个数 vv,我们计算它的数位和 xx,如果 xx 在哈希表 dd 中存在,那么我们就更新答案 ans=max(ans,d[x]+v)ans = \max(ans, d[x] + v)。然后更新哈希表 d[x]=max(d[x],v)d[x] = \max(d[x], v)

最后返回答案 ansans 即可。

由于 numsnums 中的元素最大为 10910^9,因此数位和最大为 9×9=819 \times 9 = 81,我们可以直接定义一个长度为 100100 的数组 dd 来代替哈希表。

时间复杂度 O(n×logM)O(n \times \log M),空间复杂度 O(D)O(D),其中 nn 是数组 numsnums 的长度,而 MMDD 分别是数组 numsnums 中的元素的最大值和数位和的最大值。本题中 M109M \leq 10^9D81D \leq 81

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
speed

复杂度分析

指标
时间O(n \log m)
空间O(\log m)
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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?

help

常见问题

外企场景

数位和相等数对的最大和题解:数组·哈希·扫描 | LeetCode #2342 中等