Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
C++ program to find maximum distance between two rival students after x swaps
Suppose we have four numbers n, x, a and b. There are n students in the row. There are two rivalling students among them. One of them is at position a and another one is at position b. Positions are numbered from 1 to n from left to right. We want to maximize the distance between these two students. We can perform the following operation x times: Select two adjacent students and then swap them. We have to find the maximum possible distance after x swaps.
So, if the input is like n = 5; x = 1; a = 3; b = 2, then the output will be 2, because we can swap students at position 3 and 4 so the distance between these two students is |4 - 2| = 2.
Steps
To solve this, we will follow these steps −
return minimum of (|a - b| + x) and (n - 1)
Example
Let us see the following implementation to get better understanding −
#includeusing namespace std; int solve(int n, int x, int a, int b) { return min(abs(a - b) + x, n - 1); } int main() { int n = 5; int x = 1; int a = 3; int b = 2; cout Input
5, 1, 3, 2Output
2
