classSolution { publicintmaximumSum(int[] nums) { intn= nums.length, res = -1; // nums最大1e9,9个9相加是81 // treemap中存放数位和相同的数组元素 TreeMap<Integer, Integer>[] maps = newTreeMap[82]; Arrays.setAll(maps, e -> newTreeMap<>()); for (int x : nums) { intbitSum=0, num = x; while (num > 0) { bitSum += num % 10; num /= 10; } TreeMap<Integer, Integer> map = maps[bitSum]; map.put(x, map.getOrDefault(x, 0) + 1); } for (inti=81; i >= 0; --i) { TreeMap<Integer, Integer> map = maps[i]; intkey1= -1; for (int key : map.descendingKeySet()) { if (key1 == -1 && map.get(key) >= 2) { res = Math.max(res, key * 2); break; } elseif (key1 == -1 && map.get(key) == 1) key1 = key; elseif (key1 != -1) { res = Math.max(res, key1 + key); break; } } } return res; } }
expert solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution: defmaximumSum(self, nums: List[int]) -> int: ans = -1 mx = [0] * 82# 至多 9 个 9 相加 for num in nums: # s = sum(map(int, str(num))) # 不转成 str,效率更高 s = 0 x = num while x: # 枚举 num 的每个数位 s += x % 10 x //= 10 if mx[s]: # 说明左边也有数位和等于 s 的元素 ans = max(ans, mx[s] + num) # 更新答案的最大值 mx[s] = max(mx[s], num) # 维护数位和等于 s 的最大元素 return ans