Maximum Sum Alternating Subarray | Function to find the maximum alternating sum of a subarray for the given array ; Traverse the array ; Store sum of subarrays starting at even indices ; Update sum ; Traverse the array ; Store sum of subarrays starting at odd indices ; Update sum ; Given Input ; Function call
function alternatingSum ( arr ) { var sum = 0 ; var sumSoFar = 0 ; for ( var i = 0 ; i < arr . length ; i ++ ) { if ( i % 2 == 1 ) { sumSoFar -= arr [ i ] ; } else { sumSoFar = Math . max ( sumSoFar + arr [ i ] , arr [ i ] ) ; } sum = Math . max ( sum , sumSoFar ) ; } sumSoFar = 0 ; for ( var i = 1 ; i < arr . length ; i ++ ) { if ( i % 2 == 0 ) { sumSoFar -= arr [ i ] ; } else { sumSoFar = Math . max ( sumSoFar + arr [ i ] , arr [ i ] ) ; } sum = Math . max ( sum , sumSoFar ) ; } return sum ; } var arr = new Array ( - 4 , - 10 , 3 , 5 ) ; var ans = alternatingSum ( arr ) ; document . write ( ans ) ;