forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create max-sum-of-a-pair-with-equal-sum-of-digits.py
- Loading branch information
Showing
1 changed file
with
28 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
# Time: O(nlogr), r is max(nums) | ||
# Space: O(n) | ||
|
||
# greedy | ||
class Solution(object): | ||
def maximumSum(self, nums): | ||
""" | ||
:type nums: List[int] | ||
:rtype: int | ||
""" | ||
def sum_digits(x): | ||
result = 0 | ||
while x: | ||
result += x%10 | ||
x //= 10 | ||
return result | ||
|
||
lookup = {} | ||
result = -1 | ||
for x in nums: | ||
k = sum_digits(x) | ||
if k not in lookup: | ||
lookup[k] = x | ||
continue | ||
result = max(result, lookup[k]+x) | ||
if x > lookup[k]: | ||
lookup[k] = x | ||
return result |