Skip to main content
  1. Posts/

LeetCode-2342 数位和相等数对的最大和

·1 min·

LeetCode-2342 数位和相等数对的最大和 #

Solution 1 #

遍历的同时维护当前每个数位和下的最大值, 更新答案即可.

代码如下:

class Solution:
    def maximumSum(self, nums: List[int]) -> int:
        def digit_sum(x):
            return sum([int(ch) for ch in str(x)])
        
        ans = -1
        dic = {}
        for x in nums:
            ds = digit_sum(x)
            if ds in dic:
                ans = max(ans, dic[ds] + x)
            dic[ds] = max(dic.get(ds, -inf), x)
        return ans