Maximum subarray sum with same first and last element formed by removing elements | Python3 program for the above approach ; 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
import sys NEW_LINE def maximumSubarraySum ( arr ) : NEW_LINE INDENT N = len ( arr ) ; NEW_LINE memo = { } ; NEW_LINE res = - ( sys . maxsize - 1 ) ; NEW_LINE currsum = 0 ; NEW_LINE currval = 0 ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT currval = arr [ i ] ; NEW_LINE currsum = currsum + currval ; NEW_LINE if currval in memo : NEW_LINE INDENT if ( currval > 0 ) : NEW_LINE INDENT res = max ( res , currsum - memo [ currval ] + currval ) ; NEW_LINE DEDENT else : NEW_LINE INDENT res = max ( res , currsum - memo [ currval ] + 2 * currval ) ; NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT memo [ currval ] = currsum ; NEW_LINE DEDENT if ( currval < 0 ) : NEW_LINE INDENT currsum = currsum - currval ; NEW_LINE DEDENT DEDENT return res ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ - 1 , - 3 , 4 , 0 , - 1 , - 2 ] ; NEW_LINE print ( maximumSubarraySum ( arr ) ) ; NEW_LINE DEDENT