Print the Maximum Subarray Sum | C ++ program for the above approach ; Function to print the elements of Subarray with maximum sum ; Initialize currMax and globalMax with first value of nums ; Iterate for all the elemensts of the array ; Update currMax ; Check if currMax is greater than globalMax ; Traverse in left direction to find start Index of subarray ; Decrement the start index ; Printing the elements of subarray with max sum ; Driver Code ; Given array arr [ ] ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void SubarrayWithMaxSum ( vector < int > & nums ) { int endIndex , currMax = nums [ 0 ] ; int globalMax = nums [ 0 ] ; for ( int i = 1 ; i < nums . size ( ) ; ++ i ) { currMax = max ( nums [ i ] , nums [ i ] + currMax ) ; if ( currMax > globalMax ) { globalMax = currMax ; endIndex = i ; } } int startIndex = endIndex ; while ( startIndex >= 0 ) { globalMax -= nums [ startIndex ] ; if ( globalMax == 0 ) break ; startIndex -- ; } for ( int i = startIndex ; i <= endIndex ; ++ i ) { cout << nums [ i ] << " ▁ " ; } } int main ( ) { vector < int > arr = { -2 , -5 , 6 , -2 , -3 , 1 , 5 , -6 } ; SubarrayWithMaxSum ( arr ) ; return 0 ; }