- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
#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
- Related Articles
- Find the longest common prefix between two strings after performing swaps on second string in C++
- Maximum consecutive 1s after n swaps in JavaScript
- Program to Find the Shortest Distance Between Two Points in C++
- C++ Program to find array after removal from maximum
- C program to calculate distance between two points
- Program to find number of sequences after adjacent k swaps and at most k swaps in Python
- Program to find the minimum edit distance between two strings in C++
- C++ program to find the shortest distance between two nodes in BST
- Maximum students to pass after giving bonus to everybody and not exceeding 100 marks in C++ Program
- Program to find maximum distance between empty and occupied seats in Python
- Program to find maximum distance between a pair of values in Python
- Find distance between two nodes of a Binary Tree in C++ Program
- Find maximum distance between any city and station in C++
- C++ code to find position of students after coding contest
- Maximum distance between two occurrences of same element in array in C
