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
using System ; using System . Collections . Generic ; class GFG { static void SubarrayWithMaxSum ( List < int > nums ) { int endIndex = 0 , currMax = nums [ 0 ] ; int globalMax = nums [ 0 ] ; for ( int i = 1 ; i < nums . Count ; ++ i ) { currMax = Math . 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 ) { Console . Write ( nums [ i ] + " ▁ " ) ; } } public static void Main ( String [ ] args ) { 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 ) ; } }