# Greatest Sum Divisible by Three in C++

C++Server Side ProgrammingProgramming

Suppose we have an array nums of integers, we need to find the maximum possible sum of elements of the given array such that it is divisible by three. So if the input is like [3,6,5,1,8], then the output will be 18, as the subarray is [3,6,1,8], and the sum is 18, that is divisible by 3.

To solve this, we will follow these steps −

• n := size of nums array
• create one 2d array dp of size (n + 1) x 3
• set dp[0, 0] := 0, dp[0,1] := -inf, dp[0,2] := inf
• for i in range 1 to n;
• x := nums[i - 1]
• for j in range 0 to 2, dp[i, j] := dp[i – 1, j]
• for j in range 0 to 2
• k := (x + j) mod 3
• dp[i, k] := max of dp[i, k] and dp[i – 1, j] + x
• return dp[n, 0]

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int maxSumDivThree(vector<int>& nums) {
int n = nums.size();
int dp[n+1][3];
dp[0][0] = 0;
dp[0][1] = INT_MIN;
dp[0][2] = INT_MIN;
for(int i = 1; i <= n; i++){
int x = nums[i-1];
for(int j = 0; j < 3; j++)dp[i][j] = dp[i-1][j];
for(int j = 0; j < 3; j++){
int k = (x + j) % 3;
dp[i][k] = max(dp[i][k],dp[i-1][j] + x);
}
}
return dp[n][0];
}
};
main(){
vector<int> v = {3,6,5,1,8};
Solution ob;
cout << (ob.maxSumDivThree(v));
}

## Input

[3,6,5,1,8]

## Output

18
Published on 02-May-2020 12:00:41

Advertisements