[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实现
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; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
2020-02-12 [LeetCode] 110. Balanced Binary Tree