Related Articles

# Minimum distance to visit given K points on X-axis after starting from the origin

• Last Updated : 23 Apr, 2021

Given a sorted array, arr[] of size N representing the positions of the ith point on X-axis and an integer K, the task is to find the minimum distance required to travel to visit K point starting from the origin of X-axis.

Examples :

Input: arr[]={-30, -10, 10, 20, 50}, K = 3
Output: 40
Explanation:
Moving from origin to the second point. Therefore, the total distance traveled = 10.
Moving from the second point to the third point. Therefore, total traveled = 10 + 10 = 20
Moving from the third point to the fourth point. Therefore, total distance traveled = 20 + 20 = 40
Therefore, the total distance travelled to visit K point is 40.

Input: arr[]={-1, -5, -4, -3, 6}, K = 3
Output: 6

Approach: The problem can be solved by visiting each K consecutive point and print the minimum distance traveled to visit K consecutive points. Follow the steps below to solve the problem:

• Initialize a variable, say res, to store the minimum distance traveled to visit K point.
• Initialize a variable, say dist, to store the distance traveled to visit K points.
• Traverse the array and check the following conditions.
• If the value of (arr[i] >= 0 and arr[i + K -1] >= 0) is true then update dist = max(arr[i], arr[i + K -1]).
• Otherwise, dist = abs(arr[i]) + abs(arr[i + K – 1]) + min(abs(arr[i]), abs(arr[i + K – 1])).
• Finally, update res = min(res, dist).
• Finally, print the value of res.

## C++

 `// C++ program to implement``// the above approach``  ` `#include ``using` `namespace` `std;``  ` `  ` `// Function to find the minimum distance ``// travelled to visit K point``int` `MinDistK(``int` `arr[], ``int` `N, ``int` `K)``{``      ` `      ` `    ``// Stores minimum distance travelled``    ``// to visit K point``    ``int` `res = INT_MAX;``      ` `      ` `    ``// Stores distance travelled``    ``// to visit points``    ``int` `dist = 0;``      ` `    ``// Traverse the array arr[]``    ``for` `(``int` `i = 0; i <= (N - K); i++) {``          ` `          ` `       ``// If arr[i] and arr[i + K - 1]``       ``// are positive``        ``if` `(arr[i] >= 0  && ``              ``arr[i + K - 1] >= 0) {``          ` `          ` `            ``// Update dist``            ``dist = max(arr[i], arr[i + K - 1]);``        ``}``        ``else` `{``              ` `              ` `            ``// Update dist``            ``dist = ``abs``(arr[i]) +``                   ``abs``(arr[i + K - 1])``                  ``+ min(``abs``(arr[i]),``                        ``abs``(arr[i + K - 1]));``        ``}``          ` `          ` `        ``// Update res``        ``res = min(res, dist);``    ``}``      ` `    ``return` `res;``}``  ` `  ` `// Driver Code``int` `main()``{``  ` `    ``int` `K = 3;``    ``// initial the array``    ``int` `arr[] = { -30, -10, 10, 20, 50 };``      ` `    ``int` `N = ``sizeof``(arr) / ``sizeof``(arr);``  ` `    ``cout<< MinDistK(arr, N, K);``}`

## Java

 `// Java program to implement``// the above approach``import` `java.util.*;``class` `solution{``  ` `// Function to find the minimum``// distance travelled to visit``// K point``static` `int` `MinDistK(``int` `arr[],``                    ``int` `N, ``int` `K)``{      ``  ``// Stores minimum distance``  ``// travelled to visit K point``  ``int` `res = Integer.MAX_VALUE;` `  ``// Stores distance travelled``  ``// to visit points``  ``int` `dist = ``0``;` `  ``// Traverse the array arr[]``  ``for` `(``int` `i = ``0``;``           ``i <= (N - K); i++)``  ``{``    ``// If arr[i] and arr[i + K - 1]``    ``// are positive``    ``if` `(arr[i] >= ``0`  `&& ``        ``arr[i + K - ``1``] >= ``0``)``    ``{``      ``// Update dist``      ``dist = Math.max(arr[i],``                      ``arr[i + K - ``1``]);``    ``}``    ``else``    ``{``      ``// Update dist``      ``dist = Math.abs(arr[i]) +``             ``Math.abs(arr[i + K - ``1``]) +``             ``Math.min(Math.abs(arr[i]),``             ``Math.abs(arr[i + K - ``1``]));``    ``}` `    ``// Update res``    ``res = Math.min(res, dist);``  ``}` `  ``return` `res;``}``  ` `// Driver Code``public` `static` `void` `main(String args[])``{``  ``int` `K = ``3``;``  ``// initial the array``  ``int` `arr[] = {-``30``, -``10``,``               ``10``, ``20``, ``50``};` `  ``int` `N = arr.length;``  ``System.out.println(MinDistK(arr, N, K));``}``}``  ` `// This code is contributed by bgangwar59`

## Python3

 `# Python3 program to implement``# the above approach``import` `sys` `# Function to find the minimum distance ``# travelled to visit K point``def` `MinDistK(arr, N, K):``    ` `    ``# Stores minimum distance travelled``    ``# to visit K point``    ``res ``=` `sys.maxsize``    ` `    ``# Stores distance travelled``    ``# to visit points``    ``dist ``=` `0``    ` `    ``# Traverse the array arr[]``    ``for` `i ``in` `range``(N ``-` `K ``+` `1``):``        ` `        ``# If arr[i] and arr[i + K - 1]``        ``# are positive``        ``if` `(arr[i] >``=` `0` `and` `arr[i ``+` `K ``-` `1``] >``=` `0``):``            ` `            ``# Update dist``            ``dist ``=` `max``(arr[i], arr[i ``+` `K ``-` `1``])``        ``else``:``            ` `            ``# Update dist``            ``dist ``=` `(``abs``(arr[i]) ``+` `abs``(arr[i ``+` `K ``-` `1``]) ``+``                ``min``(``abs``(arr[i]), ``abs``(arr[i ``+` `K ``-` `1``])))``          ` `        ``# Update res``        ``res ``=` `min``(res, dist)``      ` `    ``return` `res``  ` `# Driver Code``if` `__name__ ``=``=` `'__main__'``:``    ` `    ``K ``=` `3``    ` `    ``# Initial the array``    ``arr ``=` `[ ``-``30``, ``-``10``, ``10``, ``20``, ``50` `]``      ` `    ``N ``=` `len``(arr)``  ` `    ``print``(MinDistK(arr, N, K))``    ` `# This code is contributed by ipg2016107`

## C#

 `// C# program to implement``// the above approach ``using` `System;` `class` `GFG{``   ` `// Function to find the minimum``// distance travelled to visit``// K point``static` `int` `MinDistK(``int``[] arr,``                    ``int` `N, ``int` `K)``{ ``  ` `  ``// Stores minimum distance``  ``// travelled to visit K point``  ``int` `res = Int32.MaxValue;`` ` `  ``// Stores distance travelled``  ``// to visit points``  ``int` `dist = 0;`` ` `  ``// Traverse the array arr[]``  ``for``(``int` `i = 0; i <= (N - K); i++)``  ``{``    ` `    ``// If arr[i] and arr[i + K - 1]``    ``// are positive``    ``if` `(arr[i] >= 0 && ``        ``arr[i + K - 1] >= 0)``    ``{``      ` `      ``// Update dist``      ``dist = Math.Max(arr[i],``                      ``arr[i + K - 1]);``    ``}``    ``else``    ``{``      ` `      ``// Update dist``      ``dist = Math.Abs(arr[i]) +``             ``Math.Abs(arr[i + K - 1]) +``             ``Math.Min(Math.Abs(arr[i]),``             ``Math.Abs(arr[i + K - 1]));``    ``}`` ` `    ``// Update res``    ``res = Math.Min(res, dist);``  ``}``  ``return` `res;``}``   ` `// Driver Code``public` `static` `void` `Main()``{``  ``int` `K = 3;``  ` `  ``// Initial the array``  ``int``[] arr = { -30, -10, 10, 20, 50};`` ` `  ``int` `N = arr.Length;``  ` `  ``Console.WriteLine(MinDistK(arr, N, K));``}``}` `// This code is contributed by code_hunt`

## Javascript

 ``
Output
`40`

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up