Today’s Problem
https://leetcode.com/problems/max-sum-of-a-pair-with-equal-sum-of-digits/description
Intuitive Approach
For this problem, we can simulate the steps described in the problem statement to obtain the answer.
Step-by-step Method
- First, write a counting function to calculate the sum of all integers.
- Store the first two maximum values using a dictionary.
- Compare the current number with the two numbers stored in the dictionary.
- Update the
ansvalue (initially set to -1). Note that at least two numbers must be stored in the dictionary before updating the answer.
Complexity Analysis
- Time complexity: $O(Nlog(M))$, where N is the length of the sequence and M is the maximum value.
- Space complexity: $O(N)$.
Code Implementation
class Solution:
def maximumSum(self, nums: List[int]) -> int:
def cnt(x):
res = 0
while(x > 0):
res += x % 10
x //= 10
return res
dic = dict()
ans = -1
for x in nums:
nx = cnt(x)
if nx in dic:
if x > dic[nx][0]:
dic[nx][1] = dic[nx][0]
dic[nx][0] = x
if dic[nx][1] > 0:
ans = max(ans, dic[nx][0] + dic[nx][1])
elif x > dic[nx][1]:
dic[nx][1] = x
ans = max(ans, dic[nx][0] + dic[nx][1])
else:
dic.update({nx: [x, 0]})
return ans
