VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-the-city-by-using-teleporters/

⇱ Find the city by using teleporters - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find the city by using teleporters

Last Updated : 23 Jul, 2025

Given N cities numbered 1 to N. You are initially in the 1st city. The distance between two cities i, j is |Ai - Aj|. The energy lost while traveling from one city to another is equal to the distance between those two cities. Additionally, In every city i ( 1 ≤ i ≤ N-1) there is a teleporter that can teleport you from the ith city to (i+1)th city without using any energy. Your initial energy is X and you can use the teleporters at most K times. Find the farthest city you can reach if you use these teleporters optimally.

Note: Ai < Ai+1 for every i such that 1 ≤ i ≤ N-1.

Examples:

Input: N = 4, X = 2, K = 2, A[] = {0, 1, 2, 3}
Output: 4
Explanation: You can use teleporters of cities 1 and 2 and then travel from the 3rd city to the 4th city.

Approach: This can be solved with the following idea:

Using the Priority queue, we can see which cities have greater distance between them. Replacing the highest distance by teleporting and reducing K. For more clarification read the steps.

Below are the steps involved:

  • Declare a priority_queue p.
  • Iterate in array A:
    • See the distance between adjacent cities.
      • If dis <= X, we can use energy to move to next city.
      • If dis > X, we can now use teleport for maximum distance.
    • Reduce k by 1, and top of queue to X.
    • Check whether can we now move to next city or not.
  • Where k value reduced to 0, return i + 1.

Below is the implementation of the code:


Output
4

Time Complexity: O(N log N)
Auxiliary Space: O(N)

Comment