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 ; Initialize endIndex startIndex , globalStartIndex ; Iterate for all the elemensts of the array ; Update currMax and startIndex ; startIndex = i ; update the new startIndex ; Update currMax ; Update globalMax anf globalMaxStartIndex ; Printing the elements of subarray with max sum ; Driver Code ; Given array arr [ ] ; Function call
using System ; using System . Collections . Generic ; public class GFG { static void SubarrayWithMaxSum ( List < int > nums ) { int currMax = nums [ 0 ] , globalMax = nums [ 0 ] ; int endIndex = 0 ; int startIndex = 0 , globalMaxStartIndex = 0 ; for ( int i = 1 ; i < nums . Count ; ++ i ) { if ( nums [ i ] > nums [ i ] + currMax ) { currMax = nums [ i ] ; } else if ( nums [ i ] < nums [ i ] + currMax ) { currMax = nums [ i ] + currMax ; } if ( currMax > globalMax ) { globalMax = currMax ; endIndex = i ; globalMaxStartIndex = startIndex ; } } for ( int i = globalMaxStartIndex ; i <= endIndex ; ++ i ) { Console . Write ( nums [ i ] + " ▁ " ) ; } } static public void Main ( ) { List < int > arr = new List < int > ( ) ; arr . Add ( - 2 ) ; arr . Add ( - 5 ) ; arr . Add ( 6 ) ; arr . Add ( - 2 ) ; arr . Add ( - 3 ) ; arr . Add ( 1 ) ; arr . Add ( 5 ) ; arr . Add ( - 6 ) ; SubarrayWithMaxSum ( arr ) ; } }