Sum of minimum difference between consecutive elements of an array | 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
function solve ( v , n ) { let ans , ul , ll ; let first = 0 ; let second = 1 ; ll = v [ 0 ] [ first ] ; ul = v [ 0 ] [ second ] ; ans = 0 ; for ( let i = 1 ; i < n ; i ++ ) { if ( ( v [ i ] [ first ] <= ul && v [ i ] [ first ] >= ll ) || ( v [ i ] [ second ] >= ll && v [ i ] [ second ] <= ul ) ) { if ( v [ i ] [ first ] > ll ) { ll = v [ i ] [ first ] ; } if ( v [ i ] [ second ] < ul ) { ul = v [ i ] [ second ] ; } } else if ( v [ i ] [ first ] > ul ) { ans += Math . abs ( ul - v [ i ] [ first ] ) ; ul = v [ i ] [ first ] ; ll = v [ i ] [ first ] ; } else if ( v [ i ] [ second ] < ll ) { ans += Math . abs ( ll - v [ i ] [ second ] ) ; ul = v [ i ] [ second ] ; ll = v [ i ] [ second ] ; } } return ans ; } let v = [ [ 1 , 3 ] , [ 2 , 5 ] , [ 6 , 8 ] , [ 1 , 2 ] , [ 2 , 3 ] ] ; let n = 5 ; document . write ( solve ( v , n ) ) ;