![]() |
VOOZH | about |
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:
Below is the implementation of the code:
4
Time Complexity: O(N log N)
Auxiliary Space: O(N)