Skip to content

2342. Max Sum of a Pair With Equal Sum of Digits 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
 public:
  int maximumSum(vector<int>& nums) {
    constexpr int kMax = 9 * 9;  // 999,999,999
    int ans = -1;
    vector<vector<int>> count(kMax + 1);

    for (const int num : nums)
      count[getDigitSum(num)].push_back(num);

    for (vector<int>& groupNums : count) {
      if (groupNums.size() < 2)
        continue;
      ranges::sort(groupNums, greater<>());
      ans = max(ans, groupNums[0] + groupNums[1]);
    }

    return ans;
  }

 private:
  int getDigitSum(int num) {
    int digitSum = 0;
    while (num > 0) {
      digitSum += num % 10;
      num /= 10;
    }
    return digitSum;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
  public int maximumSum(int[] nums) {
    final int kMax = 9 * 9; // 999,999,999
    int ans = -1;
    List<Integer>[] count = new List[kMax + 1];

    for (int i = 0; i <= kMax; ++i)
      count[i] = new ArrayList<>();

    for (final int num : nums)
      count[getDigitSum(num)].add(num);

    for (List<Integer> groupNums : count) {
      if (groupNums.size() < 2)
        continue;
      Collections.sort(groupNums, Collections.reverseOrder());
      ans = Math.max(ans, groupNums.get(0) + groupNums.get(1));
    }

    return ans;
  }

  private int getDigitSum(int num) {
    int digitSum = 0;
    while (num > 0) {
      digitSum += num % 10;
      num /= 10;
    }
    return digitSum;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution:
  def maximumSum(self, nums: list[int]) -> int:
    kMax = 9 * 9  # 999,999,999
    ans = -1
    count = [[] for _ in range(kMax + 1)]

    for num in nums:
      count[self._getDigitSum(num)].append(num)

    for groupNums in count:
      if len(groupNums) < 2:
        continue
      groupNums.sort(reverse=True)
      ans = max(ans, groupNums[0] + groupNums[1])

    return ans

  def _getDigitSum(self, num: int) -> int:
    return sum(int(digit) for digit in str(num))