title: Maximum Profit By Buying And Selling A Share At Most K Times 1
signature: maximum_profit_by_buying_and_selling_a_share_at_most_k_times_1 <- function(price, n, k) {
source_py: def maximum_profit_by_buying_and_selling_a_share_at_most_k_times_1(price, n, k):
      profit = [[0 for i in range((n + 1))] for j in range((k + 1))]
      for i in range(1, (k + 1)):
          prevDiff = float('-inf')
          for j in range(1, n):
              prevDiff = max(prevDiff, (profit[(i - 1)][(j - 1)] - price[(j - 1)]))
              profit[i][j] = max(profit[i][(j - 1)], (price[j] + prevDiff))
      return profit[k][(n - 1)]
source_cpp: int maximum_profit_by_buying_and_selling_a_share_at_most_k_times_1(vector<int> price, int n, int k) {
    int profit [ k + 1 ] [ n + 1 ];
    for ( int i = 0;
    i <= k;
    i ++ ) profit [ i ] [ 0 ] = 0;
    for ( int j = 0;
    j <= n;
    j ++ ) profit [ 0 ] [ j ] = 0;
    for ( int i = 1;
    i <= k;
    i ++ ) {
      int prevDiff = INT_MIN;
      for ( int j = 1;
      j < n;
      j ++ ) {
        prevDiff = max ( prevDiff, profit [ i - 1 ] [ j - 1 ] - price [ j - 1 ] );
        profit [ i ] [ j ] = max ( profit [ i ] [ j - 1 ], price [ j ] + prevDiff );
      }
    }
    return profit [ k ] [ n - 1 ];
  }