Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Number of ways to form a number with maximum Ks in it

  • Last Updated : 30 Jun, 2021

Given a number N and a digit K, the task is to calculate the number of ways to form a number with the maximum number of Ks in it, where in an operation, two adjacent digits of N that sum up to K are both replaced with K.

Examples :

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 experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input :N=1454781, K=9
Output : 2
Explanation :9 can occur maximum two times after applying given operation and there are two ways of doing it. Two numbers formed are : 19479 and 14979. 194781 cannot be formed as it contains 9 only once which is not maximum.



Input : N=1007, K=8
Output : 1
Explanation : No operations can be applied on 1007.Thus, the maximum number of 8s that can be present is 0, and there is only one possible such number, which is 1007.

Approach: The following observations help in solving the problem:

  1. Considering the number as string, substrings of the form “ABAB…” where A+B=K are the only segments of the number that contribute to the answer.
  2. If the length of the contributing substring is even, there is only one way of applying the operations on them, and thus, they don’t contribute to the answer. For example, if the substring is “ABAB”, it can be changed only into “KK” to get the maximum number of K’s in the final number
  3. Otherwise, there will ⌈L/2⌉ ways to get the maximum number of Ks, where L is the length of the substrings. For example, if the substring is “ABABA”, this can be turned into the following:
    1. “KKA”
    2. “KAK”
    3. “AKK”

Follow the steps below to solve the problem:

  1. Convert N into a string, say S.
  2. Initialize a variable ans to 1, to store the final answer.
  3. Traverse the string S and for each current index i, do the following:
    1. Initialize a variable count to 1, to store the length of the current answer.
    2. Loop while i is less than length of S, and the sum of the digits at S[i] and S[i-1] is equal to K, and do the following:
      1. Increment i.
      2. Increment count.
    3. If count is odd, update ans as ans*(count+1)/2.
  4. Return ans.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to calculate number
// of ways a number can be
// formed that has the maximum number of Ks
int noOfWays(int N, int K)
{
    // convert to string
    string S = to_string(N);
    int ans = 1;
    // calculate length of subarrays
    // that can contribute to
    // the answer
    for (int i = 1; i < S.length(); i++) {
        int count = 1;
        // count length of subarray
        // where adjacent digits
        // add up to K
        while (i < S.length()
               && S[i] - '0' + S[i - 1] - '0' == K) {
            count++;
            i++;
        }
        // Current subarray can
        // contribute to the answer
        // only if it is odd
        if (count % 2)
            ans *= (count + 1) / 2;
    }
    // return the answer
    return ans;
}
// Driver code
int main()
{
    // Input
    int N = 1454781;
    int K = 9;
 
    // Function call
    cout << noOfWays(N, K) << endl;
}

Java




// Java program for tha above approach
import java.util.*;
 
class GFG{
     
// Function to calculate number
// of ways a number can be formed
// that has the maximum number of Ks
static int noOfWays(int N, int K)
{
     
    // Convert to string
    String S = String.valueOf(N);
    int ans = 1;
     
    // Calculate length of subarrays
    // that can contribute to
    // the answer
    for(int i = 1; i < S.length(); i++)
    {
        int count = 1;
         
        // Count length of subarray
        // where adjacent digits
        // add up to K
        while (i < S.length() && (int)S.charAt(i) - 48 +
              (int)S.charAt(i - 1) - 48 == K)
        {
            count++;
            i++;
        }
         
        // Current subarray can
        // contribute to the answer
        // only if it is odd
        if (count % 2 == 1)
            ans *= (count + 1) / 2;
    }
     
    // Return the answer
    return ans;
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Input
    int N = 1454781;
    int K = 9;
 
    // Function call
    System.out.print(noOfWays(N, K));
}   
}
 
// This code is contributed by susmitakundugoaldanga

Python3




# Python3 program for the above approach
 
# Function to calculate number of ways a
# number can be formed that has the
# maximum number of Ks
def noOfWays(N, K):
     
    # Convert to string
    S = str(N)
    ans = 1
     
    # Calculate length of subarrays
    # that can contribute to
    # the answer
    for i in range(1, len(S)):
        count = 1
         
        # Count length of subarray
        # where adjacent digits
        # add up to K
        while (i < len(S) and ord(S[i]) +
         ord(S[i - 1]) - 2 * ord('0') == K):
            count += 1
            i += 1
             
        # Current subarray can
        # contribute to the answer
        # only if it is odd
        if (count % 2):
            ans *= (count + 1) // 2
             
    # Return the answer
    return ans
     
# Driver code
if __name__ == '__main__':
     
    # Input
    N = 1454781
    K = 9
 
    # Function call
    print(noOfWays(N, K))
     
# This code is contributed by mohit kumar 29

C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
     
// Function to calculate number
// of ways a number can be
// formed that has the maximum number of Ks
static int noOfWays(int N, int K)
{
     
    // Convert to string
    string S = N.ToString();
    int ans = 1;
     
    // Calculate length of subarrays
    // that can contribute to
    // the answer
    for(int i = 1; i < S.Length; i++)
    {
        int count = 1;
         
        // Count length of subarray
        // where adjacent digits
        // add up to K
        while (i < S.Length && (int)S[i] - 48 +
              (int)S[i - 1] - 48 == K)
        {
            count++;
            i++;
        }
         
        // Current subarray can
        // contribute to the answer
        // only if it is odd
        if (count % 2 == 1)
            ans *= (count + 1) / 2;
    }
     
    // Return the answer
    return ans;
}
 
// Driver code
public static void Main()
{
     
    // Input
    int N = 1454781;
    int K = 9;
 
    // Function call
    Console.Write(noOfWays(N, K));
}
}
 
// This code is contributed by ipg2016107

Javascript




<script>
 
// Javascript program for the above approach
 
// Function to calculate number
// of ways a number can be formed
// that has the maximum number of Ks
function noOfWays(N, K)
{
     
    // Convert to string
    let S = N.toString();
    let ans = 1;
     
    // Calculate length of subarrays
    // that can contribute to
    // the answer
    for(let i = 1; i < S.length; i++)
    {
        let count = 1;
         
        // Count length of subarray
        // where adjacent digits
        // add up to K
        while (i < S.length && S[i].charCodeAt() - 48 +
              S[i - 1].charCodeAt() - 48 == K)
        {
            count++;
            i++;
        }
         
        // Current subarray can
        // contribute to the answer
        // only if it is odd
        if (count % 2 == 1)
            ans *= Math.floor((count + 1) / 2);
    }
     
    // Return the answer
    return ans;
}
 
// Driver Code
 
// Input
let N = 1454781;
let K = 9;
 
// Function call
document.write(noOfWays(N, K));
 
// This code is contributed by sanjoy_62
 
</script>
Output: 
2

 

Time Complexity: O(Log10N), since, the number of digits in N is Log10N
Auxiliary Space: O(1)

 




My Personal Notes arrow_drop_up
Recommended Articles
Page :