Print the Maximum Subarray Sum | Java 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
import java . util . * ; class GFG { static void SubarrayWithMaxSum ( Vector < Integer > nums ) { int endIndex = 0 , currMax = nums . get ( 0 ) ; int globalMax = nums . get ( 0 ) ; for ( int i = 1 ; i < nums . size ( ) ; ++ i ) { currMax = Math . max ( nums . get ( i ) , nums . get ( i ) + currMax ) ; if ( currMax > globalMax ) { globalMax = currMax ; endIndex = i ; } } int startIndex = endIndex ; while ( startIndex >= 0 ) { globalMax -= nums . get ( startIndex ) ; if ( globalMax == 0 ) break ; startIndex -- ; } for ( int i = startIndex ; i <= endIndex ; ++ i ) { System . out . print ( nums . get ( i ) + " ▁ " ) ; } } public static void main ( String [ ] args ) { Vector < Integer > arr = new Vector < Integer > ( ) ; 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 ) ; } }