LeetCode 1262: Greatest Sum Divisible by Three Solution

Master LeetCode problem 1262 (Greatest Sum Divisible by Three), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1262. Greatest Sum Divisible by Three

Problem Explanation

Explanation:

To find the maximum sum of elements in the array that is divisible by three, we can use dynamic programming to keep track of the maximum sum we can achieve at each step. We will consider three cases: the sum modulo 3 is 0, 1, or 2. By keeping track of these values in the dynamic programming table, we can eventually find the maximum sum that is divisible by three.

  1. Initialize a 2D dynamic programming array dp of size nums.length + 1 by 3.
  2. Iterate through each element in the input array nums.
  3. For each element, update the dynamic programming array based on the three cases mentioned above.
  4. Return the maximum sum that is divisible by three.

Time Complexity: O(n), where n is the length of the input array. Space Complexity: O(n) since we are using a 2D dynamic programming array of size n by 3.

:

Solution Code

class Solution {
    public int maxSumDivThree(int[] nums) {
        int n = nums.length;
        int[][] dp = new int[n + 1][3];
        
        for (int i = 1; i <= n; i++) {
            for (int j = 0; j < 3; j++) {
                dp[i][j] = dp[i - 1][j];
                int mod = nums[i - 1] % 3;
                int prevMod = (3 + j - mod) % 3;
                dp[i][mod] = Math.max(dp[i][mod], dp[i - 1][j] + nums[i - 1]);
            }
        }
        
        return dp[n][0];
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1262 (Greatest Sum Divisible by Three)?

This page provides optimized solutions for LeetCode problem 1262 (Greatest Sum Divisible by Three) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1262 (Greatest Sum Divisible by Three)?

The time complexity for LeetCode 1262 (Greatest Sum Divisible by Three) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1262 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1262 in Java, C++, or Python.

Back to LeetCode Solutions