[LeetCode] Max Sum of a Pair With Equal Sum of Digits

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.

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
class Solution {
int digitSum(int n) {
int res = 0;
while(n) {
res += (n%10);
n /= 10;
}
return res;
}
public:
int maximumSum(vector<int>& nums) {
unordered_map<int, vector<int>> mp;
int res = -1;
for(auto& n : nums) {
mp[digitSum(n)].push_back(n);
}
for(auto [_ , v] : mp) {
if(v.size() == 1) continue;
sort(begin(v), end(v));
int sz = v.size();
res = max(res, v[sz-1] + v[sz-2]);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/18/PS/LeetCode/max-sum-of-a-pair-with-equal-sum-of-digits/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.