Skip to content
Discussion options

You must be logged in to vote

We need to find the maximum possible sum of elements in an array such that the sum is divisible by three. The approach involves using dynamic programming to keep track of the maximum sums that yield remainders 0, 1, and 2 when divided by 3 as we iterate through the array.

Approach

  1. Dynamic Programming State Initialization: We maintain a state array dp of size 3, where:

    • dp[0] stores the maximum sum that is divisible by 3.
    • dp[1] stores the maximum sum that leaves a remainder of 1 when divided by 3.
    • dp[2] stores the maximum sum that leaves a remainder of 2 when divided by 3.
  2. Initialization: Initially, dp[0] is set to 0 (since a sum of 0 is divisible by 3), and dp[1] and dp[2] are set to…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@kovatz
Comment options

kovatz Nov 23, 2025
Collaborator

@mah-shamim
Comment options

mah-shamim Nov 23, 2025
Maintainer Author

Answer selected by kovatz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested medium Difficulty
2 participants