def max_profit(price, k):
    if not price or k <= 0:
        return 0

    n = len(price)
    if n < 2:
        return 0

    if k >= n // 2:
        profit = 0
        for i in range(1, n):
            if price[i] > price[i - 1]:
                profit += price[i] - price[i - 1]
        return profit

    buy = [-10**18] * (k + 1)
    sell = [0] * (k + 1)

    for current_price in price:
        for transaction in range(1, k + 1):
            buy[transaction] = max(buy[transaction], sell[transaction - 1] - current_price)
            sell[transaction] = max(sell[transaction], buy[transaction] + current_price)

    return sell[k]