Maximum subarray sum with same first and last element formed by removing elements | Function to find the maximum sum of sub - array ; Initialize the variables ; Traverse over the range ; Add the current value to the variable currsum for prefix sum ; Calculate the result ; Return the answer ; Driver Code
function maximumSubarraySum ( arr ) { let N = arr . length ; let memo = new Map ( ) ; let res = - 99999999 ; let currsum = 0 , currval = 0 ; for ( let i = 0 ; i < N ; ++ i ) { currval = arr [ i ] ; currsum = currsum + currval ; if ( memo . has ( currval ) ) { if ( currval > 0 ) res = Math . max ( res , currsum - memo . get ( currval ) + currval ) ; else res = Math . max ( res , currsum - memo . get ( currval ) + 2 * currval ) ; } else memo . set ( currval , currsum ) ; if ( currval < 0 ) currsum = currsum - currval ; } return res ; } let arr = [ - 1 , - 3 , 4 , 0 , - 1 , - 2 ] ; document . write ( maximumSubarraySum ( arr ) ) ;