Open In App

Find two non-intersecting String with maximum sum of difference of digits

Last Updated : 02 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a string S of length N, the task is to find two non-intersecting strings of equal length such that the sum of absolute differences of their digits is maximum and one string should start from starting index of the given string.

Note: Both strings will be of the same length.

Examples:

Input: N = 5, S = “87605”
Output: String 1 = “87”, String 2 =”05″, Difference = 10
Explanation: At index 0 of both strings: |8 – 0| = 8
At index 1 of both strings: |7 – 5| = 2
Total maximum possible absolute difference = 8 + 2 = 10, also note that string “87” is starting from starting index of given string in input and both output strings are equal in size. 

Input: N = 7, S = “987342”
Output: String 1 = “987”, String 2 = “342”, Difference = 15

  Approach: Implement the idea below to solve the problem.

The problem can be solved via traversing on left half part of the given string and applying sliding window at right side of the first string.

Follow the below illustration for a better understanding.

Illustration:

Considered N = 6 and S = 111000

Then all the possible cases for two strings will be such that they both are of equal length:

 

 It should be noted that first string will always start from 0 index of S and maximum end index can be N/2 for even N and (N / 2) – 1 for odd value of N, Only at this condition second string can have equal length of first string and second string will be at right side of first string. So we can obtain second string by applying sliding window technique.

If we get both strings then it is not hard work to get maximum absolute difference between their integer values at each index. 

Follow the steps to solve the problem:

  • Create variables max_diff, str_1, and str_2 for storing max difference, first string and second string respectively.
  • Run a loop from 0 to N/2 and follow the below-mentioned steps inside the scope of the loop:
    • Create a temp_1 variable to initialize the first string temporarily.
    •  Create a temp_2 variable to initialize the second string, Which will be obtained by traversing the input string part at the right side of temp_1.
    • Calculate the absolute integer difference of each digit of both the strings(temp_1, temp_2), If the difference is maximized till now, update max_diff with the difference obtained and update str_1 and str_2 with temp_1 and temp_2 respectively.
  • Print the value of max_diff, str_1, and str_2 in output representing max possible difference, String 1 and String 2 respectively. 

Below is the code to implement the approach:

C++




// C++ implementation
 
#include <bits/stdc++.h>
using namespace std;
 
// User defined function to obtain
// difference between two strings of
// equal length
long Difference(string X, string Y)
{
  long counter = 0;
  for (int i = X.size() - 1; i >= 0; i--) {
    counter += abs(X[i] - Y[i]);
  }
  return counter;
}
 
void findValues(string str, int n)
{
  long max_diff = INT_MIN;
  string ans_1 = "", ans_2 = "";
 
  // Loop for traversing on left half
  // part of input String
  for (int i = 0; i < (n / 2); i++) {
 
    // Variable to store first string
    string str1 = "";
 
    // Loop for initializing first string
    for (int j = 0; j <= i; j++) {
      str1 += str[j];
    }
 
    // Loop for traversing on right
    // half part of first string
    for (int k = (i + 1); k < n; k++) {
 
      // Variable to store second
      // string temporary
      string str2 = "";
 
      // Checking that end index
      // of second string should
      // not be out of bound of
      // input string Otherwise
      // will give ArrayIndexOutofBoundsException
      if ((k + i) < n) {
 
        // Loop for initializing second string
        for (int l = k; l <= k + i; l++) {
          str2 += str[l];
        }
 
        // Variable to store maximum
        // difference temporary
        long difference = Difference(str1, str2);
 
        if (difference > max_diff) {
          max_diff = difference;
          ans_1 = str1;
          ans_2 = str2;
        }
      }
    }
  }
 
  // Printing First and second non-
  // intersecting string along with
  // maximum difference between them
  cout << "String 1: " << ans_1 << endl;
  cout << "String 2: " << ans_2 << endl;
  cout << "Maximum difference: " << max_diff;
}
 
int main()
{
 
  // Code
  string str = "987342";
  int N = str.size();
 
  // Function call
  findValues(str, N);
  return 0;
}
 
// This code is contributed by ksam24000


Java




// Java code to implement the approach
 
import java.util.*;
 
class GFG {
 
    static void findValues(String str, int n)
    {
        long max_diff = Long.MIN_VALUE;
        String ans_1 = "", ans_2 = "";
 
        // Loop for traversing on left half
        // part of input String
        for (int i = 0; i < (n / 2); i++) {
 
            // Variable to store first string
            String str1 = "";
 
            // Loop for initializing first string
            for (int j = 0; j <= i; j++) {
                str1 += str.charAt(j);
            }
 
            // Loop for traversing on right
            // half part of first string
            for (int k = (i + 1); k < n; k++) {
 
                // Variable to store second
                // string temporary
                String str2 = "";
 
                // Checking that end index
                // of second string should
                // not be out of bound of
                // input string Otherwise
                // will give ArrayIndexOutofBoundsException
                if ((k + i) < n) {
 
                    // Loop for initializing second string
                    for (int l = k; l <= k + i; l++) {
                        str2 += str.charAt(l);
                    }
 
                    // Variable to store maximum
                    // difference temporary
                    long difference
                        = Difference(str1, str2);
 
                    if (difference > max_diff) {
                        max_diff = difference;
                        ans_1 = str1;
                        ans_2 = str2;
                    }
                }
            }
        }
 
        // Printing First and second non-
        // intersecting string along with
        // maximum difference between them
        System.out.println("String 1: " + ans_1 + "\n"
                           + "String 2: " + ans_2);
        System.out.println("Maximum difference: "
                           + max_diff);
    }
 
    // Driver code
    public static void main(String[] args)
    {
        String str = "987342";
        int N = str.length();
 
        // Function call
        findValues(str, N);
    }
 
    // User defined function to obtain
    // difference between two strings of
    // equal length
    static long Difference(String X, String Y)
    {
        long counter = 0;
        for (int i = X.length() - 1; i >= 0; i--) {
            counter
                += (Math.abs(X.charAt(i) - Y.charAt(i)));
        }
        return counter;
    }
}


Python3




# Python code to implement the above approach
 
# User defined function to obtain
# difference between two strings of
# equal length
def Difference(X, Y):
    counter = 0
    for i in range(len(X)-1, -1, -1):
        counter += abs(int(X[i]) - int(Y[i]))
 
    return counter
 
def findValues(Str, n):
    max_diff = float("-inf")
    ans_1 = ""
    ans_2 = ""
 
    # Loop for traversing on left
    # half part of input string
    for i in range(n//2):
       
        # Variable to store first string
        str1 = ""
         
        # Loop for initializing first string
        for j in range(i+1):
            str1 = "".join([str1, Str[j]])
 
        # Loop for traversing on right
        # half part of first string
        for k in range(i+1, n, 1):
           
            # Variable to store
            # second string temporary
            str2 = ""
             
            # Checking that end index of second string
            # should not be out of bound of input string
            # Otherwise will give array out of bound exception
            if((k + i) < n):
               
                # Loop for initializing second string
                for l in range(k, k+i+1):
                    str2 = "".join([str2, Str[l]])
 
                # Variable to store maximum
                # difference temporary
                difference = Difference(str1, str2)
 
                if(difference > max_diff):
                    max_diff = difference
                    ans_1 = str1
                    ans_2 = str2
 
    # Printing First and second non-intersecting
    # string along with maximum difference between them
    print("String 1:", ans_1)
    print("String 2:", ans_2)
    print("Maximum Difference:", max_diff)
 
 
Str = "987342"
N = len(Str)
 
# Function call
findValues(Str, N)
 
# This code is contributed by lokeshmvs21.


C#




// C# code to implement the approach
 
using System;
 
public class GFG {
 
    static void findValues(string str, int n)
    {
        long max_diff = Int64.MinValue;
        string ans_1 = "", ans_2 = "";
 
        // Loop for traversing on left half
        // part of input String
        for (int i = 0; i < (n / 2); i++) {
 
            // Variable to store first string
            string str1 = "";
 
            // Loop for initializing first string
            for (int j = 0; j <= i; j++) {
                str1 += str[j];
            }
 
            // Loop for traversing on right
            // half part of first string
            for (int k = (i + 1); k < n; k++) {
 
                // Variable to store second
                // string temporary
                string str2 = "";
 
                // Checking that end index
                // of second string should
                // not be out of bound of
                // input string Otherwise
                // will give ArrayIndexOutofBoundsException
                if ((k + i) < n) {
 
                    // Loop for initializing second string
                    for (int l = k; l <= k + i; l++) {
                        str2 += str[l];
                    }
 
                    // Variable to store maximum
                    // difference temporary
                    long difference
                        = Difference(str1, str2);
 
                    if (difference > max_diff) {
                        max_diff = difference;
                        ans_1 = str1;
                        ans_2 = str2;
                    }
                }
            }
        }
 
        // Printing First and second non-
        // intersecting string along with
        // maximum difference between them
        Console.WriteLine("String 1: " + ans_1 + "\n"
                          + "String 2: " + ans_2);
        Console.WriteLine("Maximum difference: "
                          + max_diff);
    }
 
    static public void Main()
    {
 
        // Code
        string str = "987342";
        int N = str.Length;
 
        // Function call
        findValues(str, N);
    }
 
    // User defined function to obtain
    // difference between two strings of
    // equal length
    static long Difference(String X, String Y)
    {
        long counter = 0;
        for (int i = X.Length - 1; i >= 0; i--) {
            counter += (Math.Abs(X[i] - Y[i]));
        }
        return counter;
    }
}
 
// This code is contributed by lokesh


Javascript




// Javascript implementation
 
// User defined function to obtain
// difference between two strings of
// equal length
function Difference(X, Y)
{
  let counter = 0;
  for (let i = X.length - 1; i >= 0; i--) {
    counter += Math.abs(X[i] - Y[i]);
  }
  return counter;
}
 
function findValues(str, n)
{
  let max_diff = Number.MIN_SAFE_INTEGER;
  let ans_1 = "", ans_2 = "";
 
  // Loop for traversing on left half
  // part of input String
  for (let i = 0; i < (n / 2); i++) {
 
    // Variable to store first string
    let str1 = "";
 
    // Loop for initializing first string
    for (let j = 0; j <= i; j++) {
      str1 += str[j];
    }
 
    // Loop for traversing on right
    // half part of first string
    for (let k = (i + 1); k < n; k++) {
 
      // Variable to store second
      // string temporary
      let str2 = "";
 
      // Checking that end index
      // of second string should
      // not be out of bound of
      // input string Otherwise
      // will give ArrayIndexOutofBoundsException
      if ((k + i) < n) {
 
        // Loop for initializing second string
        for (let l = k; l <= k + i; l++) {
          str2 += str[l];
        }
 
        // Variable to store maximum
        // difference temporary
        let difference = Difference(str1, str2);
 
        if (difference > max_diff) {
          max_diff = difference;
          ans_1 = str1;
          ans_2 = str2;
        }
      }
    }
  }
 
  // Printing First and second non-
  // intersecting string along with
  // maximum difference between them
  console.log("String 1: " + ans_1)
  console.log("String 1: " + ans_2)
  console.log("Maximum difference: " + max_diff);
}
 
// Code
let str = "987342";
let N = str.length;
 
// Function call
findValues(str, N);
   
// This code is contributed by Samim Hossain Mondal.


Output

String 1: 987
String 2: 342
Maximum difference: 15

Time Complexity: O(N2)
Auxiliary Space: O(1)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads