Sum of minimum difference between consecutive elements of an array | Utility pair ; function to find minimum sum of difference of consecutive element ; ul to store upper limit ll to store lower limit ; storethe lower range in ll and upper range in ul ; initialize the answer with 0 ; iterate for all ranges ; case 1 , in this case the difference will be 0 ; change upper limit and lower limit ; case 2 ; store the difference ; case 3 ; store the difference ; array of range
class pair : NEW_LINE INDENT first = 0 NEW_LINE second = 0 NEW_LINE def __init__ ( self , a , b ) : NEW_LINE INDENT self . first = a NEW_LINE self . second = b NEW_LINE DEDENT DEDENT def solve ( v , n ) : NEW_LINE INDENT ans = 0 ; ul = 0 ; ll = 0 ; NEW_LINE ll = v [ 0 ] . first NEW_LINE ul = v [ 0 ] . second NEW_LINE ans = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( v [ i ] . first <= ul and v [ i ] . first >= ll ) or ( v [ i ] . second >= ll and v [ i ] . second <= ul ) : NEW_LINE INDENT if v [ i ] . first > ll : NEW_LINE INDENT ll = v [ i ] . first NEW_LINE DEDENT if v [ i ] . second < ul : NEW_LINE INDENT ul = v [ i ] . second ; NEW_LINE DEDENT DEDENT elif v [ i ] . first > ul : NEW_LINE INDENT ans += abs ( ul - v [ i ] . first ) NEW_LINE ul = v [ i ] . first NEW_LINE ll = v [ i ] . first NEW_LINE DEDENT elif v [ i ] . second < ll : NEW_LINE INDENT ans += abs ( ll - v [ i ] . second ) ; NEW_LINE ul = v [ i ] . second ; NEW_LINE ll = v [ i ] . second ; NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT v = [ pair ( 1 , 3 ) , pair ( 2 , 5 ) , pair ( 6 , 8 ) , pair ( 1 , 2 ) , pair ( 2 , 3 ) ] NEW_LINE n = len ( v ) NEW_LINE print ( solve ( v , n ) ) NEW_LINE