Modify array by replacing every array element with minimum possible value of arr [ j ] + | j | Function to find minimum value of arr [ j ] + | j - i | for every array index ; Stores minimum of a [ j ] + | i - j | upto position i ; Stores minimum of a [ j ] + | i - j | upto position i from the end ; Traversing and storing minimum of a [ j ] + | i - j | upto i ; Traversing and storing minimum of a [ j ] + | i - j | upto i from the end ; Traversing from [ 0 , N ] and storing minimum of a [ j ] + | i - j | from starting and end ; Print the required array ; Given array arr [ ] ; Size of the array ; Function Call
function minAtEachIndex ( n , arr ) { var dp1 = Array ( n ) ; var dp2 = Array ( n ) ; var i ; dp1 [ 0 ] = arr [ 0 ] ; for ( i = 1 ; i < n ; i ++ ) dp1 [ i ] = Math . min ( arr [ i ] , dp1 [ i - 1 ] + 1 ) ; dp2 [ n - 1 ] = arr [ n - 1 ] ; for ( i = n - 2 ; i >= 0 ; i -- ) dp2 [ i ] = Math . min ( arr [ i ] , dp2 [ i + 1 ] + 1 ) ; var v = [ ] ; for ( i = 0 ; i < n ; i ++ ) v . push ( Math . min ( dp1 [ i ] , dp2 [ i ] ) ) ; v . forEach ( x => { document . write ( x + " " ) ; } ) ; } var arr = [ 1 , 4 , 2 , 5 , 3 ] ; var N = arr . length ; minAtEachIndex ( N , arr ) ;