C++ code to find minimal tiredness after meeting


Suppose we have two numbers a and b. Two friends are at position x = a and x = b on OX axis. Each of the friends can move by one along the line in any direction unlimited number of times. By moving, the tiredness of a friend changes according to the following rules: the first move increases the tiredness by 1, the second move increases the tiredness by 2 and so on. Two of them want to meet one integer point on OX axis. We have to find the minimum total tiredness they should gain.

So, if the input is like a = 5; b = 10, then the output will be 9, because one of the optimal ways is the following. The first friend should move three steps to the right, and the second friend two steps to the left. So, the total tiredness becomes 1 + 2 + 3 + 1 + 2 = 9.

Steps

To solve this, we will follow these steps −

ans := |a - b|
sum := ans / 2
return (sum + (ans mod 2)) * (sum + 1)

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
int solve(int a, int b){
   int ans = abs(a - b);
   int sum = ans / 2;
   return (sum + (ans % 2)) * (sum + 1);
}
int main(){
   int a = 5;
   int b = 10;
   cout << solve(a, b) << endl;
}

Input

5, 10

Output

9

Updated on: 29-Mar-2022

86 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements