Maximum sum of array after removing a positive or negative subarray | python 3 program for the above approach ; Function to find the maximum sum of array after removing either the contiguous positive or negative elements ; Store the total sum of array ; Store the maximum contiguous negative sum ; Store the sum of current contiguous negative elements ; Store the minimum element of array ; Traverse the array , arr [ ] ; Update the overall sum ; Store minimum element of array ; If arr [ i ] is positive ; Update temp_sum to 0 ; Add arr [ i ] to temp_sum ; Update max_neg ; If no negative element in array then remove smallest positive element ; Print the required sum ; Driver Code ; Given Input ; Function Call
import sys NEW_LINE def maxSum ( arr , n ) : NEW_LINE INDENT sum = 0 NEW_LINE max_neg = sys . maxsize NEW_LINE tempsum = 0 NEW_LINE small = sys . maxsize NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE small = min ( small , arr [ i ] ) NEW_LINE if ( arr [ i ] > 0 ) : NEW_LINE INDENT tempsum = 0 NEW_LINE DEDENT else : NEW_LINE INDENT tempsum += arr [ i ] NEW_LINE DEDENT max_neg = min ( max_neg , tempsum ) NEW_LINE DEDENT if ( max_neg == 0 ) : NEW_LINE INDENT max_neg = small NEW_LINE DEDENT print ( sum - max_neg ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ - 2 , - 3 , 4 , - 1 , - 2 , 1 , 5 , - 3 ] NEW_LINE n = len ( arr ) NEW_LINE maxSum ( arr , n ) NEW_LINE DEDENT