All prompts are owned by LeetCode. To view the prompt, click the title link above.
First completed : February 12, 2025
Last updated : February 12, 2025
Related Topics : Array, Hash Table, Sorting, Heap (Priority Queue)
Acceptance Rate : 66.01 %
My original response which was within expectations runtime wise and efficiency wise.
V2 and V3 are identical, just with V3 being V2 expanded into a few lines for readability. When doing V1 I thought it would be fun to make a oneliner version and it was a good way for me to practice my itertools and function confidence.
To go line by line explaining:
# max of the list containing: # -1 default # for each digit sum that appears in nums, what's the highest sum of those values return max( [-1] + # default [ sum(heapq.nlargest(2, [-inf] + list(group[1]))) # heapq nlargest = largest 2 values # [-inf] accounts for if a digit sum is unique # since nlargest(2, ...) will return 1 value if there's # only 1 value for group in groupby( # itertools.groupby(...) sorted(nums, key=lambda y: sum(map(int, str(y)))), # groupby doesn't always work if the # values aren't sorted in the intended # use case order (order of digit sum) key=lambda x: sum(map(int, str(x))) # key for both: sum (int value of each digit) # I found this to be much more efficient since # it's an iternal method which I presume uses # C instead of python. For a oneliner this was # the best choice at least and saved me a # few test cases of runtime. ) ] )
class Solution:
def digit_sum(self, num: int) -> int :
output = 0
while num :
output += num % 10
num //= 10
return output
def maximumSum(self, nums: List[int]) -> int:
digit_sums = [self.digit_sum(num) for num in nums]
digit_sum_indxs = defaultdict(list)
for i, x in enumerate(digit_sums) :
digit_sum_indxs[x].append(i)
output = -1
for freq, indxs in digit_sum_indxs.items() :
if len(indxs) < 2 :
continue
output = max(output, sum(sorted([nums[x] for x in indxs])[-2:]))
return output
class Solution:
def maximumSum(self, nums: List[int]) -> int:
return max([-1] + [sum(heapq.nlargest(2, [-inf] + list(group[1]))) for group in groupby(sorted(nums, key=lambda y: sum(map(int, str(y)))), key=lambda x: sum(map(int, str(x))))])
class Solution:
def maximumSum(self, nums: List[int]) -> int:
return max(
[-1] +
[
sum(heapq.nlargest(2, [-inf] + list(group[1])))
for group in groupby(
sorted(nums, key=lambda y: sum(map(int, str(y)))),
key=lambda x: sum(map(int, str(x)))
)
]
)