Fill table using above recursive formula . Note that the table is filled in diagonal fashion ( similar to http : goo . gl / PQqoS ) , from diagonal elements to table [ 0 ] [ n - 1 ] which is the result .
for ( $ gap = 0 ; $ gap < $ n ; ++ $ gap ) { for ( $ i = 0 , $ j = $ gap ; $ j < $ n ; ++ $ i , ++ $ j ) { $ mn = min1 ( $ arr , $ i , $ j ) ; $ mx = max1 ( $ arr , $ i , $ j ) ; $ table [ $ i ] [ $ j ] = ( 2 * $ mn > $ mx ) ? 0 : min ( $ table [ $ i ] [ $ j - 1 ] + 1 , $ table [ $ i + 1 ] [ $ j ] + 1 ) ; } } return $ table [ 0 ] [ $ n - 1 ] ; }