title: Maximum Profit By Buying And Selling A Share At Most Twice
signature: def maximumProfitByBuyingAndSellingAShareAtMostTwice(price: List[Int], n: Int) = {
source_py: def maximum_profit_by_buying_and_selling_a_share_at_most_twice(price, n):
      profit = ([0] * n)
      max_price = price[(n - 1)]
      for i in range((n - 2), 0, (- 1)):
          if (price[i] > max_price):
              max_price = price[i]
          profit[i] = max(profit[(i + 1)], (max_price - price[i]))
      min_price = price[0]
      for i in range(1, n):
          if (price[i] < min_price):
              min_price = price[i]
          profit[i] = max(profit[(i - 1)], (profit[i] + (price[i] - min_price)))
      result = profit[(n - 1)]
      return result
source_cpp: int maximum_profit_by_buying_and_selling_a_share_at_most_twice(vector<int> price, int n) {
    int * profit = new int [ n ];
    for ( int i = 0;
    i < n;
    i ++ ) profit [ i ] = 0;
    int max_price = price [ n - 1 ];
    for ( int i = n - 2;
    i >= 0;
    i -- ) {
      if ( price [ i ] > max_price ) max_price = price [ i ];
      profit [ i ] = max ( profit [ i + 1 ], max_price - price [ i ] );
    }
    int min_price = price [ 0 ];
    for ( int i = 1;
    i < n;
    i ++ ) {
      if ( price [ i ] < min_price ) min_price = price [ i ];
      profit [ i ] = max ( profit [ i - 1 ], profit [ i ] + ( price [ i ] - min_price ) );
    }
    int result = profit [ n - 1 ];
    delete [ ] profit;
    return result;
  }