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 ; 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
import java . util . * ; class GFG { static void SubarrayWithMaxSum ( Vector < Integer > nums ) { int currMax = nums . get ( 0 ) , globalMax = nums . get ( 0 ) ; int endIndex = 0 ; int startIndex = 0 , globalMaxStartIndex = 0 ; for ( int i = 1 ; i < nums . size ( ) ; ++ i ) { if ( nums . get ( i ) > nums . get ( i ) + currMax ) { currMax = nums . get ( i ) ; } else if ( nums . get ( i ) < nums . get ( i ) + currMax ) { currMax = nums . get ( i ) + currMax ; } if ( currMax > globalMax ) { globalMax = currMax ; endIndex = i ; globalMaxStartIndex = startIndex ; } } for ( int i = globalMaxStartIndex ; 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 ) ; } }