1262. Greatest Sum Divisible by Three LeetCode Solution

In this guide, you will get 1262. Greatest Sum Divisible by Three LeetCode Solution with the best time and space complexity. The solution to Greatest Sum Divisible by Three problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Greatest Sum Divisible by Three solution in C++
  4. Greatest Sum Divisible by Three solution in Java
  5. Greatest Sum Divisible by Three solution in Python
  6. Additional Resources
1262. Greatest Sum Divisible by Three LeetCode Solution image

Problem Statement of Greatest Sum Divisible by Three

Given an integer array nums, return the maximum possible sum of elements of the array such that it is divisible by three.

Example 1:

Input: nums = [3,6,5,1,8]
Output: 18
Explanation: Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3).
Example 2:

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

Example 3:

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

Constraints:

1 <= nums.length <= 4 * 104
1 <= nums[i] <= 104

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(1)

1262. Greatest Sum Divisible by Three LeetCode Solution in C++

class Solution {
 public:
  int maxSumDivThree(vector<int>& nums) {
    vector<int> dp(3);  // dp[i] := the maximum sum so far s.t. sum % 3 == i

    for (const int num : nums)
      for (const int sum : vector<int>(dp))
        dp[(sum + num) % 3] = max(dp[(sum + num) % 3], sum + num);

    return dp[0];
  }
};
/* code provided by PROGIEZ */

1262. Greatest Sum Divisible by Three LeetCode Solution in Java

class Solution {
  public int maxSumDivThree(int[] nums) {
    int[] dp = new int[3]; // dp[i] := the maximum sum so far s.t. sum % 3 == i

    for (final int num : nums)
      for (final int sum : dp.clone())
        dp[(sum + num) % 3] = Math.max(dp[(sum + num) % 3], sum + num);

    return dp[0];
  }
}
// code provided by PROGIEZ

1262. Greatest Sum Divisible by Three LeetCode Solution in Python

N/A
# code by PROGIEZ

Additional Resources

See also  503. Next Greater Element II LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.