Open In App

Find the city by using teleporters

Last Updated : 04 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

C++




// C++ code for the above approach:
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
 
// Function to find farthest city
int solve(int N, vector<int>& A, int x, int k)
{
 
    // Initialize a priority queue
    priority_queue<int> p;
    int i;
 
    // Start iterating in vector
    for (i = 0; i < N - 1; i++) {
 
        // Calculate dis between cities
        int y = A[i + 1] - A[i];
 
        // If dis is less than energy
        if (x >= y) {
            x -= y;
            p.push(y);
        }
        else {
            // Will try to use teleport optimally
            while (!p.empty() && p.top() > y && x < y
                   && k--) {
                x += p.top();
                p.pop();
            }
 
            // If after using teleport we are
            // able to reach city or not
            if (x < y) {
                if (k >= 1)
                    k--;
                else
                    break;
            }
            else {
                x -= y;
                p.push(y);
            }
        }
    }
 
    // Return the farthest city we can reach
    return i + 1;
}
 
// Driver code
int main()
{
 
    int N = 4;
    int x = 2;
    int k = 2;
    vector<int> A = { 0, 1, 2, 3 };
 
    // Function call
    cout << solve(N, A, x, k);
    return 0;
}


Java




// Java Code
 
import java.util.PriorityQueue;
import java.util.Vector;
 
public class CityTeleport {
 
    // Function to find farthest city
    static int solve(int N, Vector<Integer> A, int x, int k) {
        // Initialize a priority queue
        PriorityQueue<Integer> p = new PriorityQueue<>();
        int i;
 
        // Start iterating in vector
        for (i = 0; i < N - 1; i++) {
            // Calculate distance between cities
            int y = A.get(i + 1) - A.get(i);
 
            // If distance is less than energy
            if (x >= y) {
                x -= y;
                p.add(y);
            } else {
                // Will try to use teleport optimally
                while (!p.isEmpty() && p.peek() > y && x < y && k > 0) {
                    x += p.poll();
                    k--;
                }
 
                // If after using teleport we are able to reach the city or not
                if (x < y) {
                    if (k >= 1)
                        k--;
                    else
                        break;
                } else {
                    x -= y;
                    p.add(y);
                }
            }
        }
 
        // Return the farthest city we can reach
        return i + 1;
    }
 
    // Driver code
    public static void main(String[] args) {
        int N = 4;
        int x = 2;
        int k = 2;
        Vector<Integer> A = new Vector<>();
        A.add(0);
        A.add(1);
        A.add(2);
        A.add(3);
 
        // Function call
        System.out.println(solve(N, A, x, k));
    }
}
 
// This code is contributed by guptapratik


Python3




# Python Code
import heapq
 
# Function to find farthest city
def solve(N, A, x, k):
    # Initialize a priority queue
    p = []
 
    i = 0
    # Start iterating in vector
    while i < N - 1:
        # Calculate distance between cities
        y = A[i + 1] - A[i]
 
        # If distance is less than energy
        if x >= y:
            x -= y
            heapq.heappush(p, y)
        else:
            # Will try to use teleport optimally
            while p and p[0] > y and x < y and k > 0:
                x += heapq.heappop(p)
                k -= 1
 
            # If after using teleport we are able to reach the city or not
            if x < y:
                if k >= 1:
                    k -= 1
                else:
                    break
            else:
                x -= y
                heapq.heappush(p, y)
 
        i += 1
 
    # Return the farthest city we can reach
    return i + 1
 
# Driver code
if __name__ == "__main__":
    N = 4
    x = 2
    k = 2
    A = [0, 1, 2, 3]
 
    # Function call
    print(solve(N, A, x, k))
     
# This code is contributed by guptapratik


C#




using System;
using System.Collections.Generic;
 
class Program
{
    // Function to find farthest city
    static int Solve(int N, int[] A, int x, int k)
    {
        // Initialize a priority queue
        var p = new SortedSet<int>();
 
        int i = 0;
        // Start iterating in vector
        while (i < N - 1)
        {
            // Calculate distance between cities
            int y = A[i + 1] - A[i];
 
            // If distance is less than energy
            if (x >= y)
            {
                x -= y;
                p.Add(y);
            }
            else
            {
                // Will try to use teleport optimally
                while (p.Count > 0 && p.Min > y && x < y && k > 0)
                {
                    x += p.Min;
                    p.Remove(p.Min);
                    k--;
                }
 
                // If after using teleport we are able to reach the city or not
                if (x < y)
                {
                    if (k >= 1)
                        k--;
                    else
                        break;
                }
                else
                {
                    x -= y;
                    p.Add(y);
                }
            }
 
            i++;
        }
 
        // Return the farthest city we can reach
        return i + 1;
    }
 
    // Driver code
    static void Main(string[] args)
    {
        int N = 4;
        int x = 2;
        int k = 2;
        int[] A = { 0, 1, 2, 3 };
 
        // Function call
        Console.WriteLine(Solve(N, A, x, k));
    }
}


Javascript




// JavaScript code for the above approach:
 
// Function to find farthest city
function solve(N, A, x, k) {
     
    // Initialize a priority queue
    const p = [];
 
    // Start iterating in array
    for (let i = 0; i < N - 1; i++) {
         
        // Calculate dis between cities
        const y = A[i + 1] - A[i];
 
        // If dis is less than energy
        if (x >= y) {
            x -= y;
            p.push(y);
        }
        else {
            // Will try to use teleport optimally
            while (p.length > 0 && p[0] > y && x < y && k > 0) {
                x += p[0];
                p.shift();
                k--;
            }
 
            // If after using teleport we are
            // able to reach city or not
            if (x < y) {
                if (k >= 1) k--;
                else break;
            }
            else {
                x -= y;
                p.push(y);
            }
        }
    }
     
    // Return the farthest city we can reach
    return N;
}
 
// Driver code
// Inputs
const N = 4;
const x = 2;
let k = 2;
const A = [0, 1, 2, 3];
 
// Function call
console.log(solve(N, A, x, k));


Output

4



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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads