Maximum Sum Alternating Subarray | Java implementation for the above approach ; 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 ; Driver code ; Given Input ; Function call
import java . io . * ; class GFG { public static int alternatingSum ( int [ ] arr ) { int sum = 0 ; int sumSoFar = 0 ; for ( int 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 ( int 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 ; } public static void main ( String [ ] args ) { int arr [ ] = new int [ ] { - 4 , - 10 , 3 , 5 } ; int ans = alternatingSum ( arr ) ; System . out . println ( ans ) ; } }