Find the Maximum Alternate Subsequence Sum from a given array | Java program to find the maximum alternating subsequence sum for a given array ; Function to find maximum alternating subsequence sum ; Initialize sum to 0 ; Calculate the sum ; Return the final result ; Driver Code ; Array initialization ; Length of array
import java . io . * ; import java . util . * ; class GFG { static int maxAlternatingSum ( int [ ] arr , int n ) { int max_sum = 0 ; int i = 0 ; while ( i < n ) { int current_max = arr [ i ] ; int k = i ; while ( k < n && ( ( arr [ i ] > 0 && arr [ k ] > 0 ) || ( arr [ i ] < 0 && arr [ k ] < 0 ) ) ) { current_max = Math . max ( current_max , arr [ k ] ) ; k += 1 ; } max_sum += current_max ; i = k ; } return max_sum ; } public static void main ( String args [ ] ) { int [ ] arr = { 1 , 2 , 3 , 4 , - 1 , - 2 } ; int n = arr . length ; System . out . println ( maxAlternatingSum ( arr , n ) ) ; } }