[LeetCode] 2342. Max Sum of a Pair With Equal Sum of Digits

You are given a 0-indexed array nums consisting of positive integers. You can choose two indices i and j, such that i != j, and the sum of digits of the number nums[i] is equal to that of nums[j].

Return the maximum value of nums[i] + nums[j] that you can obtain over all possible indices i and j that satisfy the conditions.

Example 1:
Input: nums = [18,43,36,13,7]
Output: 54
Explanation: The pairs (i, j) that satisfy the conditions are:

  • (0, 2), both numbers have a sum of digits equal to 9, and their sum is 18 + 36 = 54.
  • (1, 4), both numbers have a sum of digits equal to 7, and their sum is 43 + 7 = 50.
    So the maximum sum that we can obtain is 54.

Example 2:
Input: nums = [10,12,19,14]
Output: -1
Explanation: There are no two numbers that satisfy the conditions, so we return -1.

Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 109

数位和相等数对的最大和。

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

请你找出所有满足条件的下标 i 和 j ,找出并返回 nums[i] + nums[j] 可以得到的 最大值 。

思路

这道题是类似 two sum 那一类的题目。题目需要我们找到两个下标不同的,但是他们的数位和是一样的数字。注意题目给的数据范围,最大是10^9,所以两层 for 循环肯定是不能过的。那么这道题我们可以用类似 two sum 的思路,用 hashmap 来存储<不同的数位和,此数位和下最大的数字>。开始遍历 input 数组,把每个数字的数位和算出来,然后和 hashmap 中的比较,如果有相同的数位和,那么就更新最大值。如果最后没发现有两个数字有相同的数位和则返回 -1。

复杂度

时间O(n)
空间O(n)

代码

Java实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public int maximumSum(int[] nums) {
int n = nums.length;
HashMap<Integer, Integer> map = new HashMap<>();
int res = -1;
for (int i = 0; i < n; i++) {
int cur = nums[i];
int digitSum = helper(cur);
if (!map.containsKey(digitSum)) {
map.put(digitSum, cur);
} else {
int last = map.get(digitSum);
res = Math.max(res, last + cur);
map.put(digitSum, Math.max(last, cur));
}
}
return res;
}

private int helper(int num) {
int res = 0;
while (num != 0) {
res += num % 10;
num /= 10;
}
return res;
}
}

[LeetCode] 2342. Max Sum of a Pair With Equal Sum of Digits
https://shurui91.github.io/posts/4089744146.html
Author
Aaron Liu
Posted on
February 11, 2025
Licensed under