Longest subarray having maximum sum | function to find the maximum sum that exists in a subarray ; function to find the length of longest subarray having sum k ; unordered_map ' um ' implemented as hash table ; traverse the given array ; accumulate sum ; when subarray starts from index '0' ; make an entry for ' sum ' if it is not present in ' um ' ; check if ' sum - k ' is present in ' um ' or not ; update maxLength ; required maximum length ; function to find the length of the longest subarray having maximum sum ; Driver program to test above
function maxSubArraySum ( arr , size ) { var max_so_far = arr [ 0 ] ; var curr_max = arr [ 0 ] ; for ( var i = 1 ; i < size ; i ++ ) { curr_max = Math . max ( arr [ i ] , curr_max + arr [ i ] ) ; max_so_far = Math . max ( max_so_far , curr_max ) ; } return max_so_far ; } function lenOfLongSubarrWithGivenSum ( arr , n , k ) { var um = new Map ( ) ; var sum = 0 , maxLen = 0 ; for ( var i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; if ( sum == k ) maxLen = i + 1 ; if ( ! um . has ( sum ) ) um . set ( sum , i ) ; if ( um . has ( sum - k ) ) { if ( maxLen < ( i - um . get ( sum - k ) ) ) maxLen = i - um . get ( sum - k ) } } return maxLen ; } function lenLongSubarrWithMaxSum ( arr , n ) { var maxSum = maxSubArraySum ( arr , n ) ; return lenOfLongSubarrWithGivenSum ( arr , n , maxSum ) ; } var arr = [ 5 , - 2 , - 1 , 3 , - 4 ] ; var n = arr . length ; document . write ( " " + lenLongSubarrWithMaxSum ( arr , n ) ) ;