Leetcode 2342: Max Sum of a Pair With Equal Sum of Digits

grid47
grid47
Exploring patterns and algorithms
Mar 17, 2024 6 min read

You are given an array nums of positive integers. You need to find two indices i and j such that i != j, and the sum of digits of the numbers nums[i] and nums[j] is the same. Return the maximum sum of nums[i] + nums[j] that you can obtain over all valid pairs of indices. If no such pair exists, return -1.
Problem
Approach
Steps
Complexity
Input: The input consists of an integer array `nums` of length `n` where `n` is between 1 and 10^5.
Example: nums = [28, 17, 45, 64, 23]
Constraints:
• 1 <= nums.length <= 10^5
• 1 <= nums[i] <= 10^9
Output: Return the maximum sum of `nums[i] + nums[j]` for two indices `i` and `j` where the sum of the digits of `nums[i]` equals the sum of the digits of `nums[j]`. If no such pair exists, return `-1`.
Example: 93
Constraints:
Goal: The goal is to find pairs of integers whose sum of digits are the same, and return the maximum sum of such pairs.
Steps:
• For each number in the array, calculate the sum of its digits.
• Store the largest number encountered for each sum of digits.
• For each new number, if its sum of digits has been seen before, calculate the sum of the current number and the previously encountered number with the same sum of digits, and update the maximum sum if necessary.
Goal: The length of `nums` is at least 1 and at most 10^5, and each element in `nums` is a positive integer between 1 and 10^9.
Steps:
• 1 <= nums.length <= 10^5
• 1 <= nums[i] <= 10^9
Assumptions:
• The input array is valid and contains positive integers.
Input: nums = [28, 17, 45, 64, 23]
Explanation: The sum of digits of 28 is 10, the sum of digits of 64 is 10 as well, so the pair (28, 64) gives the maximum sum of 93.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus