Pyramid form ( increasing then decreasing ) consecutive array using reduce operations | Returns minimum cost to form a pyramid ; Store the maximum possible pyramid height ; Maximum height at start is 1 ; For each position calculate maximum height ; Maximum height at end is 1 ; For each position calculate maximum height ; Find minimum possible among calculated values ; Find maximum height of pyramid ; Calculate cost of this pyramid ; Calculate cost of left half ; Calculate cost of right half ; Driver code
function minPyramidCost ( arr , N ) { let left = new Array ( N ) ; let right = new Array ( N ) ; left [ 0 ] = Math . min ( arr [ 0 ] , 1 ) ; for ( let i = 1 ; i < N ; ++ i ) left [ i ] = Math . min ( arr [ i ] , Math . min ( left [ i - 1 ] + 1 , i + 1 ) ) ; right [ N - 1 ] = Math . min ( arr [ N - 1 ] , 1 ) ; for ( let i = N - 2 ; i >= 0 ; -- i ) right [ i ] = Math . min ( arr [ i ] , Math . min ( right [ i + 1 ] + 1 , N - i ) ) ; let tot = new Array ( N ) ; for ( let i = 0 ; i < N ; ++ i ) tot [ i ] = Math . min ( right [ i ] , left [ i ] ) ; let max_ind = 0 ; for ( let i = 0 ; i < N ; ++ i ) if ( tot [ i ] > tot [ max_ind ] ) max_ind = i ; let cost = 0 ; let height = tot [ max_ind ] ; for ( let x = max_ind ; x >= 0 ; -- x ) { cost += arr [ x ] - height ; if ( height > 0 ) -- height ; } height = tot [ max_ind ] - 1 ; for ( let x = max_ind + 1 ; x < N ; ++ x ) { cost += arr [ x ] - height ; if ( height > 0 ) -- height ; } return cost ; } let arr = [ 1 , 2 , 3 , 4 , 2 , 1 ] ; let N = arr . length ; document . write ( minPyramidCost ( arr , N ) ) ;