title: Maximum Sum Alternating Subsequence Sum
signature: maximum_sum_alternating_subsequence_sum <- function(arr, n) {
source_py: def maximum_sum_alternating_subsequence_sum(arr, n):
      if (n == 1):
          return arr[0]
      dec = [0 for i in range((n + 1))]
      inc = [0 for i in range((n + 1))]
      dec[0] = inc[0] = arr[0]
      flag = 0
      for i in range(1, n):
          for j in range(i):
              if (arr[j] > arr[i]):
                  dec[i] = max(dec[i], (inc[j] + arr[i]))
                  flag = 1
              elif ((arr[j] < arr[i]) and (flag == 1)):
                  inc[i] = max(inc[i], (dec[j] + arr[i]))
      result = (- 2147483648)
      for i in range(n):
          if (result < inc[i]):
              result = inc[i]
          if (result < dec[i]):
              result = dec[i]
      return result
source_cpp: int maximum_sum_alternating_subsequence_sum(vector<int> arr, int n) {
    if ( n == 1 ) return arr [ 0 ];
    int dec [ n ];
    memset ( dec, 0, sizeof ( dec ) );
    int inc [ n ];
    memset ( inc, 0, sizeof ( inc ) );
    dec [ 0 ] = inc [ 0 ] = arr [ 0 ];
    int flag = 0;
    for ( int i = 1;
    i < n;
    i ++ ) {
      for ( int j = 0;
      j < i;
      j ++ ) {
        if ( arr [ j ] > arr [ i ] ) {
          dec [ i ] = max ( dec [ i ], inc [ j ] + arr [ i ] );
          flag = 1;
        }
        else if ( arr [ j ] < arr [ i ] && flag == 1 ) inc [ i ] = max ( inc [ i ], dec [ j ] + arr [ i ] );
      }
    }
    int result = INT_MIN;
    for ( int i = 0;
    i < n;
    i ++ ) {
      if ( result < inc [ i ] ) result = inc [ i ];
      if ( result < dec [ i ] ) result = dec [ i ];
    }
    return result;
  }