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

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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to find the maximum number of
// numbers divisible by 3 in a large number
#include <bits/stdc++.h>
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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to find the maximum number of 
// numbers divisible by 3 in a large number 
  
// Function to find the maximum number of 
// numbers divisible by 3 in a large number 
function MaximumNumbers($s
    // store size of the string 
    $n = strlen($s) ;
  
    // Stores last index of a remainder 
    $remIndex = array_fill(0,3,-1) ;
  
    // last visited place of remainder 
    // zero is at 0. 
    $remIndex[0] = 0; 
  
    // To store result from 0 to i 
    $res = array() ;
  
    $r = 0; 
    for ($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 
    $s = "12345"
    print(MaximumNumbers($s)) 
  
    # This code is contributed by Ryuga
?>

chevron_right


Output:

3

Another Approach:
We can use running_sum which keeps the sum of all successive integers, where none of the individual integer 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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find the maximum number
// of numbers divisible by 3 in large number 
#include <iostream>
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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to find the maximum 
// number of numbers divisible by 3 in 
// a large number
function 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 = 0; $i < strlen($num_string); $i++)
    {
        $current_num = intval($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;
}
  
// Driver Code
print(get_max_splits("12345"));
  
// This code is contributed by mits
?>

chevron_right


Output:

3


My Personal Notes arrow_drop_up

pawanasipugmailcom

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.