Leetcode 2342 Max Sum of a Pair With Equal Sum of Digits Solution in c++ | Hindi Coding Community

0

 



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.

 

Example 1:

Input: nums = [18,43,36,13,7]
Output: 54
Explanation: The pairs (i, j) that satisfy the conditions are:
- (0, 2), both numbers have a sum of digits equal to 9, and their sum is 18 + 36 = 54.
- (1, 4), both numbers have a sum of digits equal to 7, and their sum is 43 + 7 = 50.
So the maximum sum that we can obtain is 54.

Example 2:

Input: nums = [10,12,19,14]
Output: -1
Explanation: There are no two numbers that satisfy the conditions, so we return -1.

 

Constraints:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 109


C++ Code :


class Solution {
public:
int maximumSum(vector<int>& nums) {
vector<vector<int>> table(82);
for(auto n: nums){
int sum = 0, N = n;
for(; n; n/=10) sum += n%10;
table[sum].push_back(N);
}
int ans = -1;
for(auto &v: table)
if(v.size() > 1){
if(v[0] < v[1]) swap(v[0], v[1]);
for(int i = 2; i != v.size(); i++)
if(v[i] >= v[0]){v[1] = v[0]; v[0] = v[i];}
else if(v[i] > v[1]) v[1] = v[i];
ans = max(ans, v[0] + v[1]);
}
return ans;
}
};


Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !