LeetCode 2342: Max Sum of a Pair With Equal Sum of Digits Solution

Master LeetCode problem 2342 (Max Sum of a Pair With Equal Sum of Digits), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2342. Max Sum of a Pair With Equal Sum of Digits

Problem Explanation

Explanation:

To solve this problem, we can iterate through the array and calculate the sum of digits for each number. We can store these sums in a hash map where the key is the sum of digits and the value is the maximum number corresponding to that sum of digits. While iterating, for each number, we check if there is a number in the hash map with the same sum of digits. If so, we update the maximum sum found so far. Finally, we return the maximum sum or -1 if no such pair is found.

  • Algorithm:

    1. Initialize a hash map to store the maximum number for each sum of digits.
    2. Iterate through the array.
    3. For each number, calculate the sum of digits.
    4. Check if there is a number in the hash map with the same sum of digits.
    5. Update the maximum sum if a pair is found.
    6. Return the maximum sum or -1 if no pair is found.
  • Time Complexity: O(n), where n is the number of elements in the input array.

  • Space Complexity: O(n), for the hash map storing the maximum number for each sum of digits.

:

Solution Code

class Solution {
    public int maxSum(int[] nums) {
        Map<Integer, Integer> sumMap = new HashMap<>();
        int maxSum = -1;

        for (int num : nums) {
            int sum = getDigitSum(num);
            if (sumMap.containsKey(sum)) {
                maxSum = Math.max(maxSum, sumMap.get(sum) + num);
            }
            sumMap.put(sum, Math.max(sumMap.getOrDefault(sum, 0), num));
        }

        return maxSum;
    }

    private int getDigitSum(int num) {
        int sum = 0;
        while (num > 0) {
            sum += num % 10;
            num /= 10;
        }
        return sum;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2342 (Max Sum of a Pair With Equal Sum of Digits)?

This page provides optimized solutions for LeetCode problem 2342 (Max Sum of a Pair With Equal Sum of Digits) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2342 (Max Sum of a Pair With Equal Sum of Digits)?

The time complexity for LeetCode 2342 (Max Sum of a Pair With Equal Sum of Digits) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2342 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2342 in Java, C++, or Python.

Back to LeetCode Solutions