Calculate cost of visiting all array elements in increasing order | java program for the above approach ; Pair class ; Function to calculate total cost of visiting array elements in increasing order ; Stores the pair of element and their positions ; Traverse the array arr [ ] ; Push the pair { arr [ i ] , i } in v ; Sort the vector in ascending order . ; Stores the total cost ; Stores the index of last element visited ; Traverse the vector v ; Increment ans ; Assign ; Return ans ; Driver Code
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 ) ) ; } }