Problem Description
Given an integer array nums, return the maximum possible sum of elements of the array such that the sum is divisible by three. If no combination makes the sum divisible by three, return 0.
Key Insights
- The problem focuses on maximizing a sum that is divisible by three.
- Instead of trying all subsets which is inefficient, we can use dynamic programming to store the best possible sums for each remainder modulo 3.
- The idea is to maintain a state for each remainder (0, 1, 2).
- When processing each number, update the potential maximum sum for each remainder by considering the number added to previous state values.
- Use a temporary copy for state update to avoid interfering with the ongoing iteration.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the nums array. Space Complexity: O(1), since we only maintain a fixed-size array (size 3) for the dynamic programming state.
Solution
We use a dynamic programming approach where we maintain an array, dp, of size 3. Each index i in dp represents the maximum sum we can achieve that has a remainder i when divided by three. Initially, dp[0] is 0 (since a sum of 0 is divisible by three) and the other elements are set to a very low number to indicate that those remainders have not been achieved. For each number in the input list, we compute new possible sums for each remainder by adding this number to the existing sums. We update our dp array accordingly while ensuring that we do not override the results of the current iteration with the updated values immediately. Finally, dp[0] will contain the maximum sum divisible by three.