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