Reverse a subarray of the given array to minimize the sum of elements at even position | Javascript implementation to reverse a subarray of the given array to minimize the sum of elements at even position ; Function that will give the max negative value ; Check for count greater than 0 as we require only negative solution ; Function to print the minimum sum ; Taking sum of only even index elements ; Initialize two vectors v1 , v2 ; v1 will keep account for change if 1 th index element goes to 0 ; v2 will keep account for change if 1 th index element goes to 2 ; Get the max negative value ; Driver code
var N = 3 ; function after_rev ( v ) { var mini = 0 , count = 0 ; for ( var i = 0 ; i < v . length ; i ++ ) { count += v [ i ] ; if ( count > 0 ) count = 0 ; if ( mini > count ) mini = count ; } return mini ; } function print ( arr ) { var sum = 0 ; for ( var i = 0 ; i < N ; i += 2 ) sum += arr [ i ] ; var v1 = [ ] , v2 = [ ] ; for ( var i = 0 ; i + 1 < N ; i += 2 ) v1 . push ( arr [ i + 1 ] - arr [ i ] ) ; for ( var i = 1 ; i + 1 < N ; i += 2 ) v2 . push ( arr [ i ] - arr [ i + 1 ] ) ; var change = Math . min ( after_rev ( v1 ) , after_rev ( v2 ) ) ; if ( change < 0 ) sum += change ; document . write ( sum ) ; } var arr = [ 0 , 1 , 4 , 3 ] ; print ( arr ) ;