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
def calculateDistance ( arr , N ) : NEW_LINE INDENT v = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT v . append ( [ arr [ i ] , i ] ) NEW_LINE DEDENT v . sort ( ) NEW_LINE ans = 0 NEW_LINE last = 0 NEW_LINE for j in v : NEW_LINE INDENT ans += abs ( j [ 1 ] - last ) NEW_LINE last = j [ 1 ] NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 4 , 3 , 2 , 5 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE print ( calculateDistance ( arr , N ) ) NEW_LINE DEDENT