# Maximum point to convert string S to T by swapping adjacent characters

Given two strings S and T of length N, the task is to find the maximum points gained in converting the string S into string T by performing the following operation on string S:

• In one move, select an index i (1 ≤ i ≤ N−1), get (Si − Si + 1) points, and then swap Si and Si + 1

Examples:

Input: S = “321”, T = “123”
Output: 4
Explanation: One possible sequence of moves is the following:
Select i = 1. Total points = 1, and S will become “312”.
Select i = 0. Total points = 1 + 2, and S will become “132”.
Select i = 1. Total points = 1 + 2 + 1 = 4, and S will become “123”.
Hence total 4 point gained to convert a string S into string T.

Input: S = “12”, T = “21”
Output: -1
Explanation: Only one operation is possible i.e., select i = 0 and swap S and S.

Approach: The problem can be solved based on the following observation:

Observations:

Suppose we do a number of swaps to S to make it equal to T, and the element at index i in the original array is now at index posi. Let’s find the total cost incurred in the above case:

• Every time we swap element Si(of the original string) with the character Sj to its right:
• posi increases by 1, posj decreases by 1, the cost increases by Si−Sj.
• We can therefore notice that every time posi is increased by 1, the cost increases by Si. Similarly, the cost decreases by Si every time posi is decreased by 1.
• In the end, the total number of times the cost increases by Si is equal to posi − i (the cost decreases if posi − i is negative).

Therefore, we can calculate the cost contributed by each Si separately and then add them together, giving us the equation ∑Si(posi−i). See, Si * posi can be interpreted as Tj * j.

• When the elements of S are distinct, array pos is unique and the total cost is therefore fixed.
• When the elements of S are repeated, then any sequence of swaps that makes S equal T has the same total cost
• Therefore, given S and T, it suffices to find any valid mapping pos such that Tposi = Si. We can then use the equation given above to calculate the answer.

Follow the steps mentioned below to implement the above idea:

• Calculate the sum of all characters in S multiplied by their index.
• Calculate the sum of all characters in T multiplied by their index.
• Subtract the sum of S from the sum of T and print the result.

Below is the implementation of the above approach.

## C++

 `// C++ program for the above approach` `#include ` `using` `namespace` `std;`   `// Function to find maximum` `// number of point` `long` `maxPoint(string s, string t, ``int` `n)` `{` `  ``long` `sumS = 0;` `  ``long` `sumT = 0;`   `  ``for` `(``int` `i = 0; i < n; i++) {` `    ``sumS += (s[i] - ``'0'``) * 1l * (i + 1);` `  ``}`   `  ``for` `(``int` `i = 0; i < n; i++) {` `    ``sumT += (t[i] - ``'0'``) * 1l * (i + 1);` `  ``}`   `  ``return` `(sumT - sumS);` `}`   `// Driver code` `int` `main()` `{`   `  ``string S = ``"321"``;` `  ``string T = ``"123"``;` `  ``int` `N = S.length();`   `  ``// Function call` `  ``cout << (maxPoint(S, T, N));` `  ``return` `0;` `}`   `// This code is contributed by Potta Lokesh`

## Java

 `// Java code to implement the approach`   `import` `java.io.*;` `import` `java.util.*;`   `class` `GFG {`   `    ``// Function to find maximum` `    ``// number of point` `    ``public` `static` `long` `maxPoint(String s,` `                                ``String t, ``int` `n)` `    ``{` `        ``long` `sumS = ``0``;` `        ``long` `sumT = ``0``;`   `        ``for` `(``int` `i = ``0``; i < n; i++) {` `            ``sumS += s.charAt(i) * 1l * (i + ``1``);` `        ``}`   `        ``for` `(``int` `i = ``0``; i < n; i++) {` `            ``sumT += t.charAt(i) * 1l * (i + ``1``);` `        ``}`   `        ``return` `(sumT - sumS);` `    ``}`   `    ``// Driver code` `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``String S = ``"321"``;` `        ``String T = ``"123"``;` `        ``int` `N = S.length();`   `        ``// Function call` `        ``System.out.println(maxPoint(S, T, N));` `    ``}` `}`

## Python3

 `# python program for the above approach`   `# Function to find maximum no of points` `def` `maxPoints(s, t,  n):` `    ``sumS ``=` `0` `    ``sumT ``=` `0` `    ``for` `i ``in` `range``(``0``, n):` `        ``sumS ``+``=` `int``(s[i]) ``*` `(i ``+` `1``)` `    ``for` `i ``in` `range``(``0``, n):` `        ``sumT ``+``=` `int``(t[i]) ``*` `(i ``+` `1``)` `    ``return` `(sumT ``-` `sumS)`     `# Driver code` `S ``=` `"321"` `T ``=` `"123"` `N ``=` `len``(S)` `# Function call` `print``(maxPoints(S, T, N))`   `# This code is contributed by ksam24000`

## C#

 `// C# code to implement the approach` `using` `System;`   `public` `class` `GFG {`   `  ``// Function to find maximum` `  ``// number of point` `  ``public` `static` `long` `maxPoint(``string` `s, ``string` `t, ``int` `n)` `  ``{` `    ``long` `sumS = 0;` `    ``long` `sumT = 0;`   `    ``for` `(``int` `i = 0; i < n; i++) {` `      ``sumS += s[i] * 1l * (i + 1);` `    ``}`   `    ``for` `(``int` `i = 0; i < n; i++) {` `      ``sumT += t[i] * 1l * (i + 1);` `    ``}`   `    ``return` `(sumT - sumS);` `  ``}`   `  ``static` `public` `void` `Main()` `  ``{`   `    ``// Code` `    ``string` `S = ``"321"``;` `    ``string` `T = ``"123"``;` `    ``int` `N = S.Length;`   `    ``// Function call` `    ``Console.WriteLine(maxPoint(S, T, N));` `  ``}` `}`   `// This code is contributed by lokeshmvs21.`

## Javascript

 `// Javascript program for the above approach`   `// Function to find maximum` `// number of point` `function` `maxPoint(s, t, n)` `{` `  ``let sumS = 0;` `  ``let sumT = 0;`   `  ``for` `(let i = 0; i < n; i++) {` `    ``sumS += (s[i] - ``'0'``) * (i + 1);` `  ``}`   `  ``for` `(let i = 0; i < n; i++) {` `    ``sumT += (t[i] - ``'0'``) * (i + 1);` `  ``}`   `  ``return` `(sumT - sumS);` `}`   `// Driver code`   `let S = ``"321"``;` `let T = ``"123"``;` `let N = S.length;`   `// Function call` `console.log(maxPoint(S, T, N));`   `// This code is contributed by Samim Hossain Mondal.`

Output

```4

```

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

Another Approach:

1. Define a function named “maxPoint” that takes three arguments: two strings “s” and “t”, and an integer “n”.
2. Declare an integer variable named “points” and initialize it to zero.
3. Loop through each index i from 0 to n-1:
a. If the characters at index i in both strings are the same, skip to the next iteration of the loop using the “continue” keyword.
b. Otherwise, find the index j in string s where the character at index j matches the character at index i in string t.
c. If there is no such index j, return -1 from the function.
d. Otherwise, repeatedly swap adjacent characters in string s starting from index j-1 down to index i and add the difference in their ASCII codes to the “points” variable.
4. Return the “points” variable from the function.
5. In the “main” function, declare two string variables “S” and “T” and initialize them to “321” and “123”, respectively.
6. Declare an integer variable “N” and initialize it to the length of string S using the “length” method.
7. Call the “maxPoint” function with the arguments S, T, and N, and print the result to the console.
8. Return 0 to indicate successful program execution.

## C++

 `#include ` `using` `namespace` `std;`   `int` `maxPoint(string s, string t, ``int` `n)` `{` `    ``int` `points = 0;` `    ``for` `(``int` `i = 0; i < n; i++) {` `        ``if` `(s[i] == t[i])` `            ``continue``;` `        ``int` `j = i + 1;` `        ``while` `(j < n && s[j] != t[i])` `            ``j++;` `        ``if` `(j == n)` `            ``return` `-1;` `        ``while` `(j > i) {` `            ``swap(s[j], s[j - 1]);` `            ``points += s[j] - s[j - 1];` `            ``j--;` `        ``}` `    ``}` `    ``return` `points;` `}`   `int` `main()` `{` `    ``string S = ``"321"``;` `    ``string T = ``"123"``;` `    ``int` `N = S.length();` `    ``cout << maxPoint(S, T, N) << endl; ``// Output: 4` `    ``return` `0;` `}`

## Java

 `import` `java.util.*;`   `public` `class` `Main {` `    ``public` `static` `int` `maxPoint(String s, String t, ``int` `n) {` `        ``int` `points = ``0``;` `        ``char``[] sChars = s.toCharArray();` `        ``char``[] tChars = t.toCharArray();` `        ``for` `(``int` `i = ``0``; i < n; i++) {` `            ``if` `(sChars[i] == tChars[i])` `                ``continue``;` `            ``int` `j = i + ``1``;` `            ``while` `(j < n && sChars[j] != tChars[i])` `                ``j++;` `            ``if` `(j == n)` `                ``return` `-``1``;` `            ``while` `(j > i) {` `                ``char` `temp = sChars[j];` `                ``sChars[j] = sChars[j - ``1``];` `                ``sChars[j - ``1``] = temp;` `                ``points += sChars[j] - sChars[j - ``1``];` `                ``j--;` `            ``}` `        ``}` `        ``return` `points;` `    ``}`   `    ``public` `static` `void` `main(String[] args) {` `        ``String S = ``"321"``;` `        ``String T = ``"123"``;` `        ``int` `N = S.length();` `        ``System.out.println(maxPoint(S, T, N)); ``// Output: 4` `    ``}` `}`

## Python3

 `def` `maxPoint(s, t, n):` `    ``points ``=` `0` `    ``s ``=` `list``(s)` `    ``for` `i ``in` `range``(n):` `        ``if` `s[i] ``=``=` `t[i]:` `            ``continue` `        ``j ``=` `i ``+` `1` `        ``while` `j < n ``and` `s[j] !``=` `t[i]:` `            ``j ``+``=` `1` `        ``if` `j ``=``=` `n:` `            ``return` `-``1` `        ``while` `j > i:` `            ``s[j], s[j ``-` `1``] ``=` `s[j ``-` `1``], s[j]` `            ``points ``+``=` `ord``(s[j]) ``-` `ord``(s[j ``-` `1``])` `            ``j ``-``=` `1` `    ``return` `points`   `S ``=` `"321"` `T ``=` `"123"` `N ``=` `len``(S)` `print``(maxPoint(S, T, N))`

## C#

 `using` `System;`   `class` `GFG` `{` `    ``static` `int` `MaxPoint(``string` `s, ``string` `t, ``int` `n)` `    ``{` `        ``int` `points = 0;` `        ``for` `(``int` `i = 0; i < n; i++)` `        ``{` `            ``if` `(s[i] == t[i])` `                ``continue``;` `            ``int` `j = i + 1;` `            ``while` `(j < n && s[j] != t[i])` `                ``j++;` `            ``if` `(j == n)` `                ``return` `-1;` `            ``while` `(j > i)` `            ``{` `                ``char` `temp = s[j];` `                ``s = s.Remove(j, 1);` `                ``s = s.Insert(j - 1, temp.ToString());` `                ``points += s[j] - s[j - 1];` `                ``j--;` `            ``}` `        ``}` `        ``return` `points;` `    ``}`   `    ``static` `void` `Main()` `    ``{` `        ``string` `S = ``"321"``;` `        ``string` `T = ``"123"``;` `        ``int` `N = S.Length;` `        ``Console.WriteLine(MaxPoint(S, T, N)); ``// Output: 4` `    ``}` `}` `// Contributed by Aditi Tyagi`

## Javascript

 `function` `maxPoint(s, t, n) {` `    ``let points = 0;` `    ``s = [...s]` `    ``for` `(let i = 0; i < n; i++) {` `        ``if` `(s[i] == t[i])` `            ``continue``;` `        ``let j = i + 1;` `        ``while` `(j < n && s[j] != t[i])` `            ``j++;` `        ``if` `(j == n)` `            ``return` `-1;` `        ``while` `(j > i) {` `            ``[s[j], s[j - 1]] = [s[j - 1], s[j]];` `            ``points += s[j].charCodeAt(0) - s[j - 1].charCodeAt(0);` `            ``j--;` `        ``}` `    ``}` `    ``return` `points;` `}`   `let S = ``"321"``;` `let T = ``"123"``;` `let N = S.length;` `console.log(maxPoint(S, T, N));`

Output

```4

```

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

Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

Previous
Next