#3780
Maximum Sum of Three Numbers Divisible by Three
MediumArrayGreedySortingHeap (Priority Queue)Hash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
Group numbers by their remainder when divided by three, then select combinations that yield the maximum sum divisible by three.
⚙️
Algorithm
3 steps- 1Step 1: Create three lists for numbers with remainders 0, 1, and 2 when divided by 3.
- 2Step 2: Sort each list in descending order to prioritize larger numbers.
- 3Step 3: Calculate potential sums using combinations of numbers from these lists and return the maximum valid sum.
solution.py11 lines
1def maxSumDivThree(nums):
2 rem = [[], [], []]
3 for num in nums:
4 rem[num % 3].append(num)
5 for r in rem:
6 r.sort(reverse=True)
7 max_sum = 0
8 for i in range(3):
9 if len(rem[i]) >= 3:
10 max_sum = max(max_sum, sum(rem[i][:3]))
11 return max_sumℹ
Complexity note: Sorting the remainder lists takes O(n log n), while the rest is linear.
- 1Divisibility by 3 depends on the sum of remainders.
- 2Sorting helps in maximizing the sum efficiently.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.