Here in the loop we will check that whether the upcoming element of array is less than top of priority queue . If yes then we calculate the difference . After that we will remove that element and push the current element in queue . And the sum is incremented by the value of difference
for i in range ( n ) : NEW_LINE INDENT tmp = 0 NEW_LINE if not pq . empty ( ) : NEW_LINE INDENT tmp = pq . get ( ) NEW_LINE pq . put ( tmp ) NEW_LINE DEDENT if not pq . empty ( ) and tmp < a [ i ] : NEW_LINE INDENT dif = a [ i ] - tmp NEW_LINE ss += dif NEW_LINE pq . get ( ) NEW_LINE DEDENT pq . put ( a [ i ] ) NEW_LINE DEDENT return ss NEW_LINE