Maximum Displacement

Moderate
0/80
0 upvote
Asked in company
Mr. Cooper

Problem statement

You are navigating on a 1-dimensional lane, starting at position 0. You are given a string of commands, Str, and an integer N. The commands are:


'S': Move one step ahead (position +1).


'R': Move one step back (position -1).


You are required to change exactly N commands in the string. Changing 'S' to 'R' or 'R' to 'S' both count as one change. After making exactly N changes, you execute the new sequence of commands.


Your task is to find the maximum possible absolute displacement from the starting point (position 0). The displacement is the absolute value of your final position.


Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line of input contains a string Str, representing the sequence of commands.

The second line contains an integer N, representing the exact number of commands that must be changed.


Output Format:
Print a single integer representing the maximum absolute displacement achievable.


Note:
To achieve the maximum positive displacement, you should prioritize changing 'R's to 'S's. If you run out of 'R's to change but still have changes left, you'll be forced to make suboptimal changes ('S' to 'R'). A similar logic applies to achieving the maximum negative displacement. The final answer is the larger of these two possible absolute outcomes.
Sample Input 1:
SRSR
1


Sample Output 1:
2


Explanation for Sample 1:
The string is "SRSR" (2 'S', 2 'R'). We must make N=1 change.
  To maximize positive displacement: Change one 'R' to an 'S'. The new string could be "SSSR". The final position is 3 - 1 = 2.
  To maximize negative displacement: Change one 'S' to an 'R'. The new string could be "RRSR". The final position is 1 - 3 = -2.
The absolute displacements are |2| = 2 and |-2| = 2. The maximum is 2.


Sample Input 2:
S
1


Sample Output 2:
1


Explanation for Sample 2:
The string is "S" (1 'S', 0 'R'). We must make N=1 change.       The only possible change is 'S' to 'R'.
The new string is "R". The final position is -1.
The maximum absolute displacement is |-1| = 1.


Expected Time Complexity:
The expected time complexity is O(N).


Constraints:
1 <= length of Str <= 10^5
0 <= N <= length of Str

Time limit: 1 sec
Approaches (1)
Time Complexity
Space Complexity
Code Solution
(100% EXP penalty)
Maximum Displacement
Full screen
Console