Maximum difference between two elements such that larger element appears after the smaller number | The function assumes that there are at least two elements in array . The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal ; Initialize diff , current sum and max sum ; Calculate current diff ; Calculate current sum ; Update max sum , if needed ; Driver Code ; Function calling
def maxDiff ( arr , n ) : NEW_LINE INDENT diff = arr [ 1 ] - arr [ 0 ] NEW_LINE curr_sum = diff NEW_LINE max_sum = curr_sum NEW_LINE for i in range ( 1 , n - 1 ) : NEW_LINE INDENT diff = arr [ i + 1 ] - arr [ i ] NEW_LINE if ( curr_sum > 0 ) : NEW_LINE INDENT curr_sum += diff NEW_LINE DEDENT else : NEW_LINE INDENT curr_sum = diff NEW_LINE DEDENT if ( curr_sum > max_sum ) : NEW_LINE INDENT max_sum = curr_sum NEW_LINE DEDENT DEDENT return max_sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 80 , 2 , 6 , 3 , 100 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Maximum ▁ difference ▁ is " , maxDiff ( arr , n ) ) NEW_LINE DEDENT