Maximum sum of array after removing a positive or negative subarray | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maxSum ( int arr [ ] , int n ) { int sum = 0 ; int max_neg = INT_MAX ; int tempsum = 0 ; int small = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; small = min ( small , arr [ i ] ) ; if ( arr [ i ] > 0 ) { tempsum = 0 ; } else { tempsum += arr [ i ] ; } max_neg = min ( max_neg , tempsum ) ; } if ( max_neg == 0 ) { max_neg = small ; } cout << sum - max_neg ; } int main ( ) { int arr [ ] = { -2 , -3 , 4 , -1 , -2 , 1 , 5 , -3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; maxSum ( arr , n ) ; return 0 ; }