[LeetCode] Max Pair Sum in an Array

2815. Max Pair Sum in an Array

You are given a 0-indexed integer array nums. You have to find the maximum sum of a pair of numbers from nums such that the maximum digit in both numbers are equal.

Return the maximum sum or -1 if no such pair exists.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
int digit(int x) {
int res = 0;
while(x) {
res = max(res, x % 10);
x /= 10;
}
return res;
}
public:
int maxSum(vector<int>& nums) {
int res = -1;
for(int i = 0; i < nums.size(); i++) {
for(int j = i + 1; j < nums.size(); j++) {
if(digit(nums[i]) == digit(nums[j])) res = max(res, nums[i] + nums[j]);
}
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2023/08/13/PS/LeetCode/max-pair-sum-in-an-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.