Leetcode 2815. Max Pair Sum in an Array
Accepted solution but not optimized.
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.
Example 1:
Input: nums = [51,71,17,24,42]
Output: 88
Explanation:
For i = 1 and j = 2, nums[i] and nums[j] have equal maximum digits with a pair sum of 71 + 17 = 88.
For i = 3 and j = 4, nums[i] and nums[j] have equal maximum digits with a pair sum of 24 + 42 = 66.
It can be shown that there are no other pairs with equal maximum digits, so the answer is 88.
Example 2:
Input: nums = [1,2,3,4]
Output: -1
Explanation: No pair exists in nums with equal maximum digits.
class Solution {
public:
int maxSum(vector<int>& nums) {
int maxAnswer = -1;
vector<int>largestDigit ={};
int numsSize = nums.size();
for(int i=0; i < numsSize; i++){
largestDigit.push_back(maxInt(nums[i]));
}
for(int i=0; i < numsSize; i++){
for(int j=i+1; j < numsSize; j++){
if(largestDigit[i] == largestDigit[j])
{
maxAnswer = max(maxAnswer, nums[i] + nums[j]);
}
}
}
return maxAnswer;
}
int maxInt(int n)
{
int maxInteger = 0;
while(n > 0){
maxInteger = max(maxInteger, n%10);
n = n/10;
//372/10 = 37---devide (2)---mode
}
return maxInteger;
}
};
Optimized version as per Vlad https://leetcode.com/votrubac/
class Solution {
public:
int maxSum(vector<int>& nums) {
int maxAnswer = -1;
int digitArr[10] = {};
int numsSize = nums.size();
for(int i=0; i < numsSize; i++){
int maxDigit = getMaxDigit(nums[i]);
//if digit array already has the value for a given digit
if(digitArr[maxDigit])
{
maxAnswer = max(maxAnswer, digitArr[maxDigit] + nums[i]);
}
digitArr[maxDigit] = max(digitArr[maxDigit], nums[i]);
}
return maxAnswer;
}
int getMaxDigit(int n)
{
int maxDigitValue = 0;
while(n > 0){
maxDigitValue = max(maxDigitValue, n%10);
n = n/10;
//372/10 = 37---devide (2)---mode
}
return maxDigitValue;
}
};