Calculate cost of visiting all array elements in increasing order | 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
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 ) ) ;