Skip to content

Commit 7fd8e32

Browse files
committed
Sync LeetCode submission Runtime - 621 ms (8.64%), Memory - 33.6 MB (69.14%)
1 parent 8239bb5 commit 7fd8e32

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<p>You are given a <strong>0-indexed</strong> array <code>nums</code> consisting of <strong>positive</strong> integers. You can choose two indices <code>i</code> and <code>j</code>, such that <code>i != j</code>, and the sum of digits of the number <code>nums[i]</code> is equal to that of <code>nums[j]</code>.</p>
2+
3+
<p>Return <em>the <strong>maximum</strong> value of </em><code>nums[i] + nums[j]</code><em> that you can obtain over all possible indices </em><code>i</code><em> and </em><code>j</code><em> that satisfy the conditions.</em></p>
4+
5+
<p>&nbsp;</p>
6+
<p><strong class="example">Example 1:</strong></p>
7+
8+
<pre>
9+
<strong>Input:</strong> nums = [18,43,36,13,7]
10+
<strong>Output:</strong> 54
11+
<strong>Explanation:</strong> The pairs (i, j) that satisfy the conditions are:
12+
- (0, 2), both numbers have a sum of digits equal to 9, and their sum is 18 + 36 = 54.
13+
- (1, 4), both numbers have a sum of digits equal to 7, and their sum is 43 + 7 = 50.
14+
So the maximum sum that we can obtain is 54.
15+
</pre>
16+
17+
<p><strong class="example">Example 2:</strong></p>
18+
19+
<pre>
20+
<strong>Input:</strong> nums = [10,12,19,14]
21+
<strong>Output:</strong> -1
22+
<strong>Explanation:</strong> There are no two numbers that satisfy the conditions, so we return -1.
23+
</pre>
24+
25+
<p>&nbsp;</p>
26+
<p><strong>Constraints:</strong></p>
27+
28+
<ul>
29+
<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
30+
<li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>
31+
</ul>
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# Approach: Hashmap
2+
3+
# m = number of unique sums in `nums`
4+
# Time: O(n * log n)
5+
# Space: O(m)
6+
7+
class Solution:
8+
def maximumSum(self, nums: List[int]) -> int:
9+
digit_sum_dict = {}
10+
max_sum = -1
11+
12+
for num in nums:
13+
digit_sum = sum(int(digit) for digit in str(num))
14+
15+
if digit_sum in digit_sum_dict:
16+
max_sum = max(max_sum, digit_sum_dict[digit_sum] + num)
17+
digit_sum_dict[digit_sum] = max(digit_sum_dict[digit_sum], num)
18+
else:
19+
digit_sum_dict[digit_sum] = num
20+
21+
return max_sum
22+

0 commit comments

Comments
 (0)