Calculate cost of visiting all array elements in increasing order
Last Updated :
04 Jan, 2023
Given an array arr[] consisting of N integers, the task is to find the total cost of visiting all the array elements in ascending order, starting from 0, if the cost of a move from index i to the index j is the absolute difference between i and j.
Examples:
Input: arr[ ] = { 4, 3, 2, 5, 1 }
Output: 11
Explanation:
Jump from index 0 to index 4. Cost = abs(4 – 0) = 4.
Jump from index 4 to index 2. Cost = abs(4 – 2) = 2.
Jump from index 2 to index1. Cost = abs(2 – 1) = 1.
Jump from index 1 to index 0. Cost = abs(1 – 0) = 1.
Jump from index 0 to index 3. Cost = abs(0 – 3) = 3.
Therefore, the total cost of visiting all array elements in ascending order = (4 + 2 + 1 + 1 + 3 = 11).
Input: arr[ ] = { 1, 2, 3 }
Output: 2
Approach: The idea is to use the concept of sorting of the vector of pairs. Follow the steps below to solve the problem:
- Initialize a pair of vector<pair<int, int> >, say v, to store the pairs of elements and their respective positions.
- Traverse the array arr[] and push the pair {arr[i], i} in the vector v.
- Initialize two variables, say ans = 0 and last = 0, to store the total cost required and the index of the last visited element.
- Sort the vector of pairs in ascending order.
- Traverse the vector v and increment ans by abs(v[i].second – last). Update last as last = arr[i].second.
- After completing the above steps, print the answer obtained as ans.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int calculateDistance( int arr[], int N)
{
vector<pair< int , int > > v;
for ( int i = 0; i < N; i++)
v.push_back({ arr[i], i });
sort(v.begin(), v.end());
int ans = 0;
int last = 0;
for ( auto j : v) {
ans += abs (j.second - last);
last = j.second;
}
return ans;
}
int main()
{
int arr[] = { 4, 3, 2, 5, 1 };
int N = sizeof (arr) / sizeof (arr[0]);
cout << calculateDistance(arr, N);
}
|
Java
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG {
static class Pair {
int first;
int second;
Pair( int first, int second)
{
this .first = first;
this .second = second;
}
}
static int calculateDistance( int arr[], int N)
{
Pair v[] = new Pair[N];
for ( int i = 0 ; i < N; i++)
v[i] = new Pair(arr[i], i);
Arrays.sort(v, (p1, p2) -> {
if (p1.first != p2.first)
return p1.first - p2.first;
return p1.second - p2.second;
});
int ans = 0 ;
int last = 0 ;
for (Pair j : v) {
ans += Math.abs(j.second - last);
last = j.second;
}
return ans;
}
public static void main(String[] args)
{
int arr[] = { 4 , 3 , 2 , 5 , 1 };
int N = arr.length;
System.out.println(calculateDistance(arr, N));
}
}
|
Python3
def calculateDistance(arr, N):
v = []
for i in range (N):
v.append([arr[i], i])
v.sort()
ans = 0
last = 0
for j in v:
ans + = abs (j[ 1 ] - last)
last = j[ 1 ]
return ans
if __name__ = = "__main__" :
arr = [ 4 , 3 , 2 , 5 , 1 ]
N = len (arr)
print (calculateDistance(arr, N))
|
C#
using System;
using System.Linq;
namespace GFG
{
class Program
{
class Pair
{
public int first;
public int second;
public Pair( int first, int second)
{
this .first = first;
this .second = second;
}
}
static int CalculateDistance( int [] arr, int N)
{
Pair[] v = new Pair[N];
for ( int i = 0; i < N; i++)
{
v[i] = new Pair(arr[i], i);
}
Array.Sort(v, (p1, p2) =>
{
if (p1.first != p2.first)
{
return p1.first - p2.first;
}
return p1.second - p2.second;
});
int ans = 0;
int last = 0;
foreach (Pair j in v)
{
ans += Math.Abs(j.second - last);
last = j.second;
}
return ans;
}
static void Main( string [] args)
{
int [] arr = { 4, 3, 2, 5, 1 };
int N = arr.Length;
Console.WriteLine(CalculateDistance(arr, N));
}
}
}
|
Javascript
<script>
function calculateDistance(arr, N)
{
var v = [];
for ( var i = 0; i < N; i++)
{
v.push([ arr[i], i ]);
}
v = v.sort();
var ans = 0;
var last = 0;
for ( var i = 0; i < N; i++)
{
ans += Math.abs(v[i][1] - last);
last = v[i][1];
}
return ans;
}
var arr = [ 4, 3, 2, 5, 1 ];
var N = arr.length;
document.write(calculateDistance(arr, N));
</script>
|
Time Complexity: O(N*log(N))
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...