Find the minimum sum of distance to A and B from any integer point in a ring of size N in Python

PythonServer Side ProgrammingProgramming

Suppose we have a ring, which is made of few numbers from 1 to N. We also have tow numbers A and B. Now, we can stand at any place (say x) and perform the count operation with respect of the total sum of the distance (say Z = distance from X to A + distance from X to B). We have to select X such that Z is minimized. At the end return the value of Z. We have to keep in mind that X will not be same as A and B.

So, if the input is like N = 30, A = 10, B = 20, then the output will be 10 as by selecting X = 15, distance from X to A is 5, and distance from X to B is 5. So, total distance = 5 + 5 = 10.

To solve this, we will follow these steps −

  • if a > b is non-zero, then

    • swap a and b

  • clock_wise_dist := b - a

  • counter_clock_wise_dist :=(a - 1) +(n - b + 1)

  • minimum_dist := minimum of clock_wise_dist, counter_clock_wise_dist

  • if minimum_dist is same as 1, then

    • return 3

  • return minimum_dist

Example 

Let us see the following implementation to get better understanding −

 Live Demo

def get_min_z(n, a, b):
   if (a > b):
      a, b = b, a
   clock_wise_dist = b - a
   counter_clock_wise_dist = (a - 1) + (n - b + 1)
   minimum_dist = min(clock_wise_dist, counter_clock_wise_dist)
   if (minimum_dist == 1):
      return 3
   return minimum_dist
n = 30
a = 10
b = 20
print(get_min_z(n, a, b))

Input

30, 10, 20

Output

10
raja
Updated on 20-Aug-2020 08:40:14

Advertisements