<p>Given an integer array <code>nums</code>, return <em>the <strong>maximum possible sum </strong>of elements of the array such that it is divisible by three</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [3,6,5,1,8]
<strong>Output:</strong> 18
<strong>Explanation:</strong> Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3).</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [4]
<strong>Output:</strong> 0
<strong>Explanation:</strong> Since 4 is not divisible by 3, do not pick any number.
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,2,3,4,4]
<strong>Output:</strong> 12
<strong>Explanation:</strong> Pick numbers 1, 3, 4 and 4 their sum is 12 (maximum sum divisible by 3).
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 4 * 10<sup>4</sup></code></li>
	<li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>
</ul>

class Solution:
    # [3 6 5 1 8]
    # [1 3 5 6 8]
    # [1 0 2 0 2], {1:[0], 0:[1 3], 2:[2,4]}
    # totalSum = 2 => we need to subtract a 2 or we need to subtract two 1s
    # totalSum = 0 => sum is divisible by three
    # totalSum = 1 => subtract the lowest possible one or the two lowest possible twos or return 0
    # totalSum = 2 => subtract the lowest possible two or the two lowest possible ones or return 0
    # [1 1 3 4 5]
    # totalSum = 14 => residue = 2
    # [1 1 0 1 2]
    def maxSumDivThree(self, nums: List[int]) -> int:
        dct = defaultdict(list)
        length = len(nums)
        nums.sort()
        for i in range(length):
            dct[nums[i] % 3].append(i)
        totalSum = sum(nums)
        print(dct)
        if totalSum % 3 == 0:
            return totalSum
        if totalSum % 3 == 1:
            toSub = float('inf')
            if 1 in dct:
                toSub = min(toSub, nums[dct[1][0]])
            if 2 in dct and len(dct[2]) > 1:
                toSub = min(toSub, nums[dct[2][0]] + nums[dct[2][1]])
            if toSub == float('inf'):
                return 0
            return totalSum - toSub
        if totalSum % 3 == 2:
            toSub = float('inf')
            if 1 in dct and len(dct[1]) > 1:
                toSub = min(toSub, nums[dct[1][0]] + nums[dct[1][1]])
            if 2 in dct:
                toSub = min(toSub, nums[dct[2][0]])
            if toSub == float('inf'):
                return 0
            return totalSum - toSub
            

        
22300