Maximum subarray sum possible after removing at most one subarray | Function to find maximum subarray sum possible after removing at most one subarray ; Calculate the preSum [ ] array ; Update the value of sum ; Update the value of maxSum ; Update the value of preSum [ i ] ; Calculate the postSum [ ] array ; Update the value of sum ; Update the value of maxSum ; Update the value of postSum [ i ] ; Stores the resultant maximum sum of subarray ; Update the value of ans ; Print the resultant sum ; Driver Code
function maximumSum ( arr , n ) { let preSum = Array . from ( { length : n } , ( _ , i ) => 0 ) ; let sum = 0 ; let maxSum = 0 ; for ( let i = 0 ; i < n ; i ++ ) { sum = Math . max ( arr [ i ] , sum + arr [ i ] ) ; maxSum = Math . max ( maxSum , sum ) ; preSum [ i ] = maxSum ; } sum = 0 ; maxSum = 0 ; let postSum = Array . from ( { length : n + 1 } , ( _ , i ) => 0 ) ; for ( let i = n - 1 ; i >= 0 ; i -- ) { sum = Math . max ( arr [ i ] , sum + arr [ i ] ) ; maxSum = Math . max ( maxSum , sum ) ; postSum [ i ] = maxSum ; } let ans = 0 ; for ( let i = 0 ; i < n ; i ++ ) { ans = Math . max ( ans , preSum [ i ] + postSum [ i + 1 ] ) ; } document . write ( ans ) ; } let arr = [ 7 , 6 , - 1 , - 4 , - 5 , 7 , 1 ] ; maximumSum ( arr , arr . length ) ;