Discovering Minimal journey time to Nearest metropolis from Present location

0
10
Adv1


Adv2

Enhance Article

Save Article

Like Article

Enhance Article

Save Article

Given an integer N representing the variety of cities close to you together with two arrays pos[] representing the place of town and time[] representing the time required to maneuver 1 unit of distance for a specific metropolis, the duty is to search out the minimal time required to go to any metropolis the place you’re presently at cur place.

Examples:

Enter: N = 3, cur = 4, pos[] = [1, 5, 6], time[] = [2, 3, 1]
Output: 2
Clarification:

  • Whole time taken by the first taxi shall be: (4-1)*2 = 6
  • Whole time taken by the 2nd taxi shall be: (5-4)*3 = 3
  • Whole time taken by the third taxi shall be: (6-4)*1 = 2

So, the minimal time shall be 2 sec.

Enter: N = 2, cur = 1, pos[] = [1, 6], time[] = [10, 3]
Output: 0
Clarification:

  • Whole time taken by the first taxi shall be: (1-1)*10 = 0
  • Whole time taken by the 2nd taxi shall be: (6-1)*3 = 15

So, the minimal time shall be 0 sec.

Strategy: This may be solved with the next thought:

Decide the bottom period of time required by you to achieve every metropolis by first calculating absolutely the distance between you and every metropolis.

Beneath are the steps concerned within the implementation of the code:

  • Run a loop from 0 to N(variety of taxis).
  • Preserve calculating the gap after which multiply it by the point taken by you to journey every metropolis per unit distance.
  • Now maintain storing the minimal time.
  • Return within the min time doable.

Beneath is the code implementation of the above code:

Java

import java.util.*;

public class GFG {

  

    

    

    public static int minimumTime(int N, int cur, int[] pos,

                                  int[] time)

    {

  

        

        

        int mn = (int)1e9;

  

        

        for (int i = 0; i < N; i++) {

  

            

            

            

            int dist = Math.abs(pos[i] - cur);

  

            

            

            

            

            

            mn = Math.min(mn, dist * time[i]);

        }

  

        

        

        return mn;

    }

  

    

    public static void essential(String[] args)

    {

  

        int N = 3;

        int cur = 4;

        int[] pos = { 1, 5, 6 };

        int[] time = { 2, 3, 1 };

  

        

        int minTime = minimumTime(N, cur, pos, time);

        System.out.println(minTime);

    }

}

Time Complexity: O(N)
Auxilairy House: O(1) 

Adv3