# Possible cuts of a number such that maximum parts are divisible by 3

Last Updated : 07 Aug, 2022

Given a Large number N ( number of digits in N can be up to 105). The task is to find the cuts required of a number such that maximum parts are divisible by 3.
Examples:

```Input: N = 1269
Output: 3
Cut the number as 12|6|9. So, 12, 6, 9 are the
three numbers which are divisible by 3.

Input: N = 71
Output: 0
However, we make cuts there is no such number
that is divisible by 3. ```

Approach:
Let’s calculate the values of the array res[0â€¦n], where res[i] is the answer for the prefix of the length i. Obviously, res[0]:=0, since for the empty string (the prefix of the length 0) the answer is 0.
For i>0 one can find res[i] in the following way:

• Let’s look at the last digit of the prefix of length i. It has index i-1. Either it doesn’t belong to segment divisible by 3, or it belongs.
• If it doesn’t belong, it means last digit can’t be used, so res[i]=res[i-1]. If it belongs then find shortest s[j..i-1] that is divisible by 3 and try to update res[i] with the value res[j]+1.
• A number is divisible by 3, if and only if the sum of its digits is divisible by 3. So the task is to find the shortest suffix of s[0â€¦i-1] with the sum of digits divisible by 3. If such suffix is s[j..i-1] then s[0..j-1] and s[0..i-1] have the same remainder of the sum of digits modulo 3.
• Let’s maintain remIndex[0..2]- an array of the length 3, where remIndex[r] is the length of the longest processed prefix with the sum of digits equal to r modulo 3. Use remIndex[r]= -1 if there is no such prefix. It is easy to see that j=remIndex[r] where r is the sum of digits on the ith prefix modulo 3.
• So to find the maximal j<=i-1 that substring s[j..i-1] is divisible by 3, just check that remIndex[r] not equals to -1 and use j=remIndex[r], where r is the sum of digits on the i-th prefix modulo 3.
• It means that to handle case that the last digit belongs to divisible by 3 segment, try to update res[i] with value res[remIndex[r]]+1. In other words, just do if (remIndex[r] != -1) => res[i] = max(res[i], res[remIndex[r]] + 1).

Below is the implementation of the above approach:

## C++

 `// CPP program to find the maximum number of` `// numbers divisible by 3 in a large number` `#include ` `using` `namespace` `std;`   `// Function to find the maximum number of` `// numbers divisible by 3 in a large number` `int` `MaximumNumbers(string s)` `{` `    ``// store size of the string` `    ``int` `n = s.length();`   `    ``// Stores last index of a remainder` `    ``vector<``int``> remIndex(3, -1);`   `    ``// last visited place of remainder` `    ``// zero is at 0.` `    ``remIndex[0] = 0;`   `    ``// To store result from 0 to i` `    ``vector<``int``> res(n + 1);`   `    ``int` `r = 0;` `    ``for` `(``int` `i = 1; i <= n; i++) {`   `        ``// get the remainder` `        ``r = (r + s[i-1] - ``'0'``) % 3;`   `        ``// Get maximum res[i] value` `        ``res[i] = res[i-1];` `        ``if` `(remIndex[r] != -1)` `            ``res[i] = max(res[i], res[remIndex[r]] + 1);`   `        ``remIndex[r] = i+1;` `    ``}`   `    ``return` `res[n];` `}`   `// Driver Code` `int` `main()` `{` `    ``string s = ``"12345"``;` `    ``cout << MaximumNumbers(s);` `    ``return` `0;` `}`

## Java

 `// Java program to find the maximum number of` `// numbers divisible by 3 in a large number` `import` `java.util.*;`   `class` `GFG` `{` `    `  `// Function to find the maximum number of` `// numbers divisible by 3 in a large number` `static` `int` `MaximumNumbers(String s)` `{` `    ``// store size of the string` `    ``int` `n = s.length();`   `    ``// Stores last index of a remainder` `    ``int` `[] remIndex={-``1``, -``1``, -``1``};`   `    ``// last visited place of remainder` `    ``// zero is at 0.` `    ``remIndex[``0``] = ``0``;`   `    ``// To store result from 0 to i` `    ``int``[] res = ``new` `int``[n + ``1``];`   `    ``int` `r = ``0``;` `    ``for` `(``int` `i = ``1``; i <= n; i++)` `    ``{`   `        ``// get the remainder` `        ``r = (r + s.charAt(i-``1``) - ``'0'``) % ``3``;`   `        ``// Get maximum res[i] value` `        ``res[i] = res[i - ``1``];` `        ``if` `(remIndex[r] != -``1``)` `            ``res[i] = Math.max(res[i],` `                    ``res[remIndex[r]] + ``1``);`   `        ``remIndex[r] = i + ``1``;` `    ``}`   `    ``return` `res[n];` `}`   `// Driver Code` `public` `static` `void` `main (String[] args)` `{` `    ``String s = ``"12345"``;` `    ``System.out.println(MaximumNumbers(s));` `}` `}`   `// This code is contributed by ` `// chandan_jnu`

## Python3

 `# Python3 program to find the maximum ` `# number of numbers divisible by 3 in ` `# a large number` `import` `math as mt `   `# Function to find the maximum number ` `# of numbers divisible by 3 in a ` `# large number` `def` `MaximumNumbers(string):`   `    ``# store size of the string` `    ``n ``=` `len``(string)`   `    ``# Stores last index of a remainder` `    ``remIndex ``=` `[``-``1` `for` `i ``in` `range``(``3``)]`   `    ``# last visited place of remainder` `    ``# zero is at 0.` `    ``remIndex[``0``] ``=` `0`   `    ``# To store result from 0 to i` `    ``res ``=` `[``-``1` `for` `i ``in` `range``(n ``+` `1``)]`   `    ``r ``=` `0` `    ``for` `i ``in` `range``(n ``+` `1``):` `        `  `        ``# get the remainder` `        ``r ``=` `(r ``+` `ord``(string[i ``-` `1``]) ``-` `                 ``ord``(``'0'``)) ``%` `3`   `        ``# Get maximum res[i] value` `        ``res[i] ``=` `res[i ``-` `1``]` `        ``if` `(remIndex[r] !``=` `-``1``):` `            ``res[i] ``=` `max``(res[i], res[remIndex[r]] ``+` `1``)`   `        ``remIndex[r] ``=` `i ``+` `1` `    `  `    ``return` `res[n]`   `# Driver Code` `s``=` `"12345"` `print``(MaximumNumbers(s))`   `# This code is contributed` `# by Mohit kumar 29`

## C#

 `// C# program to find the maximum number of ` `// numbers divisible by 3 in a large number . ` `using` `System;`   `class` `GFG ` `{ ` `    `  `    ``// Function to find the maximum number of ` `    ``// numbers divisible by 3 in a large number ` `    ``static` `int` `MaximumNumbers(String s) ` `    ``{ ` `        ``// store size of the string ` `        ``int` `n = s.Length; `   `        ``// Stores last index of a remainder ` `        ``int` `[] remIndex = {-1, -1, -1}; `   `        ``// last visited place of remainder ` `        ``// zero is at 0. ` `        ``remIndex[0] = 0; `   `        ``// To store result from 0 to i ` `        ``int``[] res = ``new` `int``[n + 1]; `   `        ``int` `r = 0; ` `        ``for` `(``int` `i = 1; i <= n; i++) ` `        ``{ `   `            ``// get the remainder ` `            ``r = (r + s[i-1] - ``'0'``) % 3; `   `            ``// Get maximum res[i] value ` `            ``res[i] = res[i - 1]; ` `            ``if` `(remIndex[r] != -1) ` `                ``res[i] = Math.Max(res[i], ` `                        ``res[remIndex[r]] + 1); `   `            ``remIndex[r] = i + 1; ` `        ``} ` `        ``return` `res[n]; ` `    ``} `   `    ``// Driver Code ` `    ``public` `static` `void` `Main (String[] args) ` `    ``{ ` `        ``String s = ``"12345"``; ` `        ``Console.WriteLine(MaximumNumbers(s)); ` `    ``} ` `} `   `// This code has been contributed by ` `// PrinciRaj1992`

## PHP

 ``

## Javascript

 ``

Output:

`3`

Time Complexity: O(n), since there runs a loop from 1 to n.

Auxiliary Space: O(n), since extra space has been taken in the form of an array of size of n the space takes in linear.

Another Approach:
We can use running_sum which keeps the sum of all successive integers, where none of the individual integers is divisible by 3. we can pass through each integer one by one and do the following:

1. If the integer is divisible by 3 or the running_sum is non-zero and divisible by 3, increment the counter and reset running_sum.
2. In case the integer is not divisible by 3, keep a track of sum of all such successive integers.

## C++

 `// C++ program to find the maximum number` `// of numbers divisible by 3 in large number ` `#include ` `using` `namespace` `std;`   `int` `get_max_splits(string num_string)` `{ ` `    ``// This will contain the count of the splits ` `    ``int` `count = 0, current_num;` `    `  `    ``// This will keep sum of all successive ` `    ``// integers, when they are indivisible by 3 ` `    ``int` `running_sum = 0;` `    ``for` `(``int` `i = 0; i < num_string.length(); i++)` `    ``{` `        ``current_num = num_string[i] - ``'0'``; ` `        ``running_sum += current_num; ` `        `  `        ``// This is the condition of finding a split ` `        ``if` `(current_num % 3 == 0 || ` `        ``(running_sum != 0 && running_sum % 3 == 0))` `        ``{ ` `            ``count += 1;` `            ``running_sum = 0;` `        ``}` `    ``}` `    `  `    ``return` `count;` `}`   `// Driver code` `int` `main()` `{` `    ``cout << get_max_splits(``"12345"``) << endl; ` `    ``return` `0;` `}`   `// This code is contributed by Rituraj Jain`

## Java

 `// Java program to find the maximum number` `// of numbers divisible by 3 in large number ` `class` `GFG` `{`   `static` `int` `get_max_splits(String num_String)` `{ ` `    ``// This will contain the count of the splits ` `    ``int` `count = ``0``, current_num;` `    `  `    ``// This will keep sum of all successive ` `    ``// integers, when they are indivisible by 3 ` `    ``int` `running_sum = ``0``;` `    ``for` `(``int` `i = ``0``; i < num_String.length(); i++)` `    ``{` `        ``current_num = num_String.charAt(i) - ``'0'``; ` `        ``running_sum += current_num; ` `        `  `        ``// This is the condition of finding a split ` `        ``if` `(current_num % ``3` `== ``0` `|| ` `        ``(running_sum != ``0` `&& running_sum % ``3` `== ``0``))` `        ``{ ` `            ``count += ``1``;` `            ``running_sum = ``0``;` `        ``}` `    ``}` `    ``return` `count;` `}`   `// Driver code` `public` `static` `void` `main(String[] args)` `{` `    ``System.out.print(get_max_splits(``"12345"``) +``"\n"``); ` `}` `}`   `// This code is contributed by 29AjayKumar`

## Python3

 `# Python3 program to find the maximum ` `# number of numbers divisible by 3 in ` `# a large number` `def` `get_max_splits(num_string):` `    `  `    ``# This will contain the count of the splits` `    ``count ``=` `0` `    `  `     ``# This will keep sum of all successive ` `     ``# integers, when they are indivisible by 3` `    ``running_sum ``=` `0` `    ``for` `i ``in` `range``(``len``(num_string)):` `        ``current_num ``=` `int``(num_string[i])` `        ``running_sum ``+``=` `current_num` `        `  `        ``# This is the condition of finding a split` `        ``if` `current_num ``%` `3` `=``=` `0` `or` `(running_sum !``=` `0` `and` `running_sum ``%` `3` `=``=` `0``): ` `            ``count ``+``=` `1` `            ``running_sum ``=` `0` `    ``return` `count`     `print` `get_max_splits(``"12345"``)`   `# This code is contributed by Amit Ranjan`

## C#

 `// C# program to find the maximum number` `// of numbers divisible by 3 in large number ` `using` `System;`   `class` `GFG` `{`   `static` `int` `get_max_splits(String num_String)` `{ ` `    ``// This will contain the count of the splits ` `    ``int` `count = 0, current_num;` `    `  `    ``// This will keep sum of all successive ` `    ``// integers, when they are indivisible by 3 ` `    ``int` `running_sum = 0;` `    ``for` `(``int` `i = 0; i < num_String.Length; i++)` `    ``{` `        ``current_num = num_String[i] - ``'0'``; ` `        ``running_sum += current_num; ` `        `  `        ``// This is the condition of finding a split ` `        ``if` `(current_num % 3 == 0 || ` `        ``(running_sum != 0 && running_sum % 3 == 0))` `        ``{ ` `            ``count += 1;` `            ``running_sum = 0;` `        ``}` `    ``}` `    ``return` `count;` `}`   `// Driver code` `public` `static` `void` `Main(String[] args)` `{` `    ``Console.Write(get_max_splits(``"12345"``) +``"\n"``); ` `}` `}`   `// This code is contributed by 29AjayKumar`

## PHP

 ``

## Javascript

 ``

Output:

`3`

Time Complexity: O(n) only one traversal of the array is needed so the algorithm takes overall linear time

Auxiliary Space: O(1) since no extra array is used so it takes constant space