Minimum sum possible by assigning every increasing / decreasing consecutive pair with values in that order | Function to print the minimum sum of values assigned to each element of the array as per given conditions ; Initialize vectors with value 1 ; Traverse from left to right ; Update if ans [ i ] > ans [ i - 1 ] ; Traverse from right to left ; Update as ans [ i ] > ans [ i + 1 ] if arr [ i ] > arr [ i + 1 ] ; Find the minimum sum ; Print the sum ; Given array arr [ ] ; Function Call
function minSum ( arr , n ) { let ans = new Array ( n ) . fill ( 1 ) ; for ( let i = 1 ; i < n ; i ++ ) { if ( arr [ i ] > arr [ i - 1 ] ) { ans [ i ] = Math . max ( ans [ i ] , ans [ i - 1 ] + 1 ) ; } } for ( let i = n - 2 ; i >= 0 ; i -- ) { if ( arr [ i ] > arr [ i + 1 ] ) { ans [ i ] = Math . max ( ans [ i ] , ans [ i + 1 ] + 1 ) ; } } let s = 0 ; for ( let x in ans ) { s = s + ans [ x ] ; } document . write ( s + " " ) ; } let arr = [ 1 , 2 , 2 ] ; let N = arr . length ; minSum ( arr , N ) ;