Given an integer array arr of size N. The task is to find the maximum number of splits such that each split has sum divisible by 3. It is not necessary that all splits are divisible by 3, the task is to just maximize the number of splits which are divisible by 3.
Input: arr  = [2, 36, 1, 9, 2, 0, 1, 8, 1]
The array can be splited into 4 parts:
[2, 36, 1] Sum = 39
 Sum = 9
[2, 0, 1] Sum = 3
[8, 1] Sum = 9
All splits are divisible by 3 and there cannot be more than 4 splits which are divisible by 3.
Input: arr  = [40, 40, 40, 5]
Array can be splits into only two parts
[40, 40] Sum = 80.
[40, 5] Sum = 45.
The sum of the second split is divisible by 3 hence only one split is divisible by 3 so the output is 1.
One observation that can be made easily is that it is easier to work with the array if we take modulo of every element by 3. Because it would not have any effect in the splits. Now the problem can be solved using Dynamic Programming .
- Let dp[i] signifies maximum number of splits at position i .
- Then calculate the prefix sums modulo 3.
- So if a segment has sum divisible by 3 and its left and right prefix sum will also be same.
- Another thing to notice is that prefix sums modulo 3 can be either 0, 1 or 2 . So if the current prefix sum modulo 3 is 1. Choose the left pointer as the right most index which has prefix sum 1. Or ignore the segment and move on.
dp[i] = max( dp[right most index from 0 to i with prefix sum same as i] + 1, dp[i-1])
dp[i-1] means we are not considering i as right pointer of some segment .
dp[right most index from 0 to i with prefix sum same as i]+1 means i is a right pointer of the segment and total number of splits will be the total number of splits at the left pointer of the segment + 1 (for this segment) .
Below is the implementation of the above approach:
Time Complexity: O (N)
Auxiliary Space: O (N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with industry experts, please refer DSA Live Classes