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

    n = len(price)
    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 = [float('-inf')] * (k + 1)
    sell = [0] * (k + 1)

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

    return sell[k]