#1262

Greatest Sum Divisible by Three

Medium
ArrayDynamic ProgrammingGreedySortingDynamic ProgrammingGreedy Algorithms
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution uses dynamic programming to keep track of the maximum sums that can be achieved with different remainders when divided by 3. This allows us to efficiently compute the maximum sum without checking all subsets.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize an array dp of size 3 with all zeros to store maximum sums for remainders 0, 1, and 2.
  2. 2Step 2: Iterate through each number in the input array.
  3. 3Step 3: For each number, update the dp array based on the current number's contribution to each remainder.
solution.py8 lines
1def maxSumDivThree(nums):
2    dp = [0, 0, 0]
3    for num in nums:
4        temp = dp[:]
5        for i in range(3):
6            temp[(i + num) % 3] = max(temp[(i + num) % 3], dp[i] + num)
7        dp = temp
8    return dp[0]

Complexity note: The time complexity is O(n) because we iterate through the array once, and the space complexity is O(1) since we only use a fixed-size array to store the maximum sums.

  • 1Using dynamic programming allows us to efficiently track potential sums without generating all subsets.
  • 2Understanding remainders when dividing by 3 helps in optimizing the solution.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.