Find the minimum of maximum length of a jump required to reach the last island in exactly k jumps in Python

PythonServer Side ProgrammingProgramming

Suppose we have an array A of numbers, in A the i-th number is the position where an island is present, and another integer k is given (1 ≤ k < N). Now, a person is standing on the 0-th island and has to reach the last island, by jumping from one island to another in exactly k jumps, we have to find the minimum of the maximum length of a jump a person will make in his/her journey. We have to keep in mind that the position of all the islands are given in ascending order.

So, if the input is like A = [7, 20, 41, 48], k = 2, then the output will be 28, as there are two ways to reach the last island 7 to 20 to 48, here the maximum distance between any two consecutive islands is between 48 and 20 that is 28. And 7 to 41 to 48 here the maximum distance between any two consecutive islands is between 41 and 7 that is 34. So, the minimum of 28 and 34 is 28.

To solve this, we will follow these steps −

  • Define a function isPossible() . This will take arr,dist, k

  • n := size of arr

  • req := 0

  • current := 0

  • previous := 0

  • for i in range 0 to n, do

    • while current is not same as n and (arr[current] - arr[previous]) <= dist, do

      • current := current + 1

    • req := req + 1

    • if current is same as n, then

      • come out from the loop

    • previous := current - 1

  • if current is not same as n, then

    • return False

  • if req <= k, then

    • return True

  • return False

  • From the main method, do the following −

  • n := size of arr

  • left := 0

  • right := last element of arr

  • ans := 0

  • while left −= right, do

    • mid := (left + right) / 2;

    • if isPossible(arr, mid, k) is non-zero, then

      • ans := mid

      • right := mid - 1

    • otherwise,

      • left := mid + 1

  • return ans

Example 

Let us see the following implementation to get better understanding −

def isPossible(arr,dist, k) :
   n = len(arr)
   req = 0
   current = 0
   previous = 0
   for i in range(0, n):
      while (current != n and (arr[current] - arr[previous]) <= dist):
         current += 1
      req += 1
      if (current == n):
         break
      previous = current - 1
   if (current != n):
      return False
   if (req <= k):
      return True
   return False
def minimum_distance(arr, k):
   n = len(arr)
   left = 0
   right = arr[-1]
   ans = 0
   while (left <= right):
      mid = (left + right) // 2;
      if (isPossible(arr, mid, k)):
         ans = mid
         right = mid - 1
      else:
         left = mid + 1
   return ans
arr = [7, 20, 41, 48]
k = 2
print(minimum_distance(arr, k))

Input

[7, 20, 41, 48] , 2

Output

28
raja
Published on 20-Aug-2020 08:32:53
Advertisements