Print the Maximum Subarray Sum | 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 ; Given array arr [ ] ; Function call
function SubarrayWithMaxSum ( nums ) { var endIndex , currMax = nums [ 0 ] ; var globalMax = nums [ 0 ] ; for ( var i = 1 ; i < nums . length ; ++ i ) { currMax = Math . max ( nums [ i ] , nums [ i ] + currMax ) ; if ( currMax > globalMax ) { globalMax = currMax ; endIndex = i ; } } var startIndex = endIndex ; while ( startIndex >= 0 ) { globalMax -= nums [ startIndex ] ; if ( globalMax == 0 ) break ; startIndex -- ; } for ( var i = startIndex ; i <= endIndex ; ++ i ) { document . write ( nums [ i ] + " " ) ; } } var arr = [ - 2 , - 5 , 6 , - 2 , - 3 , 1 , 5 , - 6 ] ; SubarrayWithMaxSum ( arr ) ;