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++
#include <bits/stdc++.h>
using namespace std;
int MaximumNumbers(string s)
{
int n = s.length();
vector< int > remIndex(3, -1);
remIndex[0] = 0;
vector< int > res(n + 1);
int r = 0;
for ( int i = 1; i <= n; i++) {
r = (r + s[i-1] - '0' ) % 3;
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];
}
int main()
{
string s = "12345" ;
cout << MaximumNumbers(s);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int MaximumNumbers(String s)
{
int n = s.length();
int [] remIndex={- 1 , - 1 , - 1 };
remIndex[ 0 ] = 0 ;
int [] res = new int [n + 1 ];
int r = 0 ;
for ( int i = 1 ; i <= n; i++)
{
r = (r + s.charAt(i- 1 ) - '0' ) % 3 ;
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];
}
public static void main (String[] args)
{
String s = "12345" ;
System.out.println(MaximumNumbers(s));
}
}
|
Python3
import math as mt
def MaximumNumbers(string):
n = len (string)
remIndex = [ - 1 for i in range ( 3 )]
remIndex[ 0 ] = 0
res = [ - 1 for i in range (n + 1 )]
r = 0
for i in range (n + 1 ):
r = (r + ord (string[i - 1 ]) -
ord ( '0' )) % 3
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]
s = "12345"
print (MaximumNumbers(s))
|
C#
using System;
class GFG
{
static int MaximumNumbers(String s)
{
int n = s.Length;
int [] remIndex = {-1, -1, -1};
remIndex[0] = 0;
int [] res = new int [n + 1];
int r = 0;
for ( int i = 1; i <= n; i++)
{
r = (r + s[i-1] - '0' ) % 3;
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];
}
public static void Main (String[] args)
{
String s = "12345" ;
Console.WriteLine(MaximumNumbers(s));
}
}
|
PHP
<?php
function MaximumNumbers( $s )
{
$n = strlen ( $s ) ;
$remIndex = array_fill (0,3,-1) ;
$remIndex [0] = 0;
$res = array () ;
$r = 0;
for ( $i = 1; $i <= $n ; $i ++) {
$r = ( $r + $s [ $i -1] - '0' ) % 3;
$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 ];
}
$s = "12345" ;
print (MaximumNumbers( $s ))
# This code is contributed by Ryuga
?>
|
Javascript
<script>
function MaximumNumbers(s)
{
let n = s.length;
let remIndex=[-1, -1, -1];
remIndex[0] = 0;
let res = new Array(n + 1);
for (let i=0;i<res.length;i++)
{
res[i]=0;
}
let r = 0;
for (let i = 1; i <= n; i++)
{
r = (r + s[i-1].charCodeAt(0) - '0' .charCodeAt(0)) % 3;
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];
}
let s = "12345" ;
document.write(MaximumNumbers(s));
</script>
|
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:
- 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.
- In case the integer is not divisible by 3, keep a track of sum of all such successive integers.
C++
#include <iostream>
using namespace std;
int get_max_splits(string num_string)
{
int count = 0, current_num;
int running_sum = 0;
for ( int i = 0; i < num_string.length(); i++)
{
current_num = num_string[i] - '0' ;
running_sum += current_num;
if (current_num % 3 == 0 ||
(running_sum != 0 && running_sum % 3 == 0))
{
count += 1;
running_sum = 0;
}
}
return count;
}
int main()
{
cout << get_max_splits( "12345" ) << endl;
return 0;
}
|
Java
class GFG
{
static int get_max_splits(String num_String)
{
int count = 0 , current_num;
int running_sum = 0 ;
for ( int i = 0 ; i < num_String.length(); i++)
{
current_num = num_String.charAt(i) - '0' ;
running_sum += current_num;
if (current_num % 3 == 0 ||
(running_sum != 0 && running_sum % 3 == 0 ))
{
count += 1 ;
running_sum = 0 ;
}
}
return count;
}
public static void main(String[] args)
{
System.out.print(get_max_splits( "12345" ) + "\n" );
}
}
|
Python3
def get_max_splits(num_string):
count = 0
running_sum = 0
for i in range ( len (num_string)):
current_num = int (num_string[i])
running_sum + = current_num
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" )
|
C#
using System;
class GFG
{
static int get_max_splits(String num_String)
{
int count = 0, current_num;
int running_sum = 0;
for ( int i = 0; i < num_String.Length; i++)
{
current_num = num_String[i] - '0' ;
running_sum += current_num;
if (current_num % 3 == 0 ||
(running_sum != 0 && running_sum % 3 == 0))
{
count += 1;
running_sum = 0;
}
}
return count;
}
public static void Main(String[] args)
{
Console.Write(get_max_splits( "12345" ) + "\n" );
}
}
|
PHP
<?php
function get_max_splits( $num_string )
{
$count = 0;
$running_sum = 0;
for ( $i = 0; $i < strlen ( $num_string ); $i ++)
{
$current_num = intval ( $num_string [ $i ]);
$running_sum += $current_num ;
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" ));
?>
|
Javascript
<script>
function get_max_splits(num_String)
{
let count = 0, current_num;
let running_sum = 0;
for (let i = 0; i < num_String.length; i++)
{
current_num = num_String[i].charCodeAt(0) -
'0' .charCodeAt(0);
running_sum += current_num;
if (current_num % 3 == 0 ||
(running_sum != 0 && running_sum % 3 == 0))
{
count += 1;
running_sum = 0;
}
}
return count;
}
document.write(get_max_splits( "12345" ) + "<br>" );
</script>
|
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
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...