
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Maximum Distance Between Two Rival Students After X Swaps in C++
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 −
#include <bits/stdc++.h> using 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 << solve(n, x, a, b) << endl; }
Input
5, 1, 3, 2
Output
2