[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 |
|