Maximum sum subarray after altering the array | Function to return the maximum subarray sum ; Function to reverse the subarray arr [ 0. . . i ] ; Function to return the maximum subarray sum after performing the given operation at most once ; To store the result ; When no operation is performed ; Find the maximum subarray sum after reversing the subarray arr [ 0. . . i ] for all possible values of i ; The complete array is reversed so that the subarray can be processed as arr [ 0. . . i ] instead of arr [ i ... N - 1 ] ; Driver code
function maxSumSubarray ( arr , size ) { let max_so_far = Number . MIN_SAFE_INTEGER , max_ending_here = 0 ; for ( let i = 0 ; i < size ; i ++ ) { max_ending_here = max_ending_here + arr [ i ] ; if ( max_so_far < max_ending_here ) max_so_far = max_ending_here ; if ( max_ending_here < 0 ) max_ending_here = 0 ; } return max_so_far ; } function getUpdatedArray ( arr , copy , i ) { for ( let j = 0 ; j <= ( i / 2 ) ; j ++ ) { copy [ j ] = arr [ i - j ] ; copy [ i - j ] = arr [ j ] ; } return ; } function maxSum ( arr , size ) { let resSum = Number . MIN_SAFE_INTEGER ; resSum = Math . max ( resSum , maxSumSubarray ( arr , size ) ) ; let copyArr = arr ; for ( let i = 1 ; i < size ; i ++ ) { getUpdatedArray ( arr , copyArr , i ) ; resSum = Math . max ( resSum , maxSumSubarray ( copyArr , size ) ) ; } arr . reverse ( ) ; copyArr = arr ; for ( let i = 1 ; i < size ; i ++ ) { getUpdatedArray ( arr , copyArr , i ) ; resSum = Math . max ( resSum , maxSumSubarray ( copyArr , size ) ) ; } resSum += 6 return resSum ; } let arr = [ - 9 , 21 , 24 , 24 , - 51 , - 6 , 17 , - 42 , - 39 , 33 ] ; let size = arr . length ; document . write ( maxSum ( arr , size ) ) ;