2342: Max-Sum-of-a-Pair-With-Equal-Sum-of-Digits
Medium
You can just use a hashmap, mp
, to keep
track of the maximum integer for each
digit sum, index
. However, since we know there is a
maximum number of digit sums (81
since 1 <= nums[i] <= 10^9
, meaning largest
digit sum is 9 * 9 = 81
) we can just use an array of
constant size instead of an
unordered_map
.
Then:
Code:
class Solution {
public:
int maximumSum(vector<int>& nums) {
int mp[82];
(mp, -1, sizeof(int)*82);
memsetint ans = 0;
for (int i = 0; i < nums.size(); ++i) {
int index = 0;
int val = nums[i];
while(nums[i] > 0) {
+= nums[i]%10;
index [i] /= 10;
nums}
if (mp[index] == -1) {
[index] = val;
mp} else {
= max(ans, mp[index] + val);
ans [index] = max(val, mp[index]);
mp}
}
return ans == 0 ? -1 : ans;
}
};