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
< ? php function solve ( $ v , $ n ) { $ ans ; $ ul ; $ ll ; $ first = 0 ; $ second = 1 ; $ ll = $ v [ 0 ] [ $ first ] ; $ ul = $ v [ 0 ] [ $ second ] ; $ ans = 0 ; for ( $ i = 1 ; $ i < $ n ; $ i ++ ) { if ( ( $ v [ $ i ] [ $ first ] <= $ ul and $ v [ $ i ] [ $ first ] >= $ ll ) or ( $ v [ $ i ] [ $ second ] >= $ ll and $ 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 += abs ( $ ul - $ v [ $ i ] [ $ first ] ) ; $ ul = $ v [ $ i ] [ $ first ] ; $ ll = $ v [ $ i ] [ $ first ] ; } else if ( $ v [ $ i ] [ $ second ] < $ ll ) { $ ans += abs ( $ ll - $ v [ $ i ] [ $ second ] ) ; $ ul = $ v [ $ i ] [ $ second ] ; $ ll = $ v [ $ i ] [ $ second ] ; } } return $ ans ; } $ v = array ( array ( 1 , 3 ) , array ( 2 , 5 ) , array ( 6 , 8 ) , array ( 1 , 2 ) , array ( 2 , 3 ) ) ; $ n = 5 ; echo ( solve ( $ v , $ n ) ) ; ? >