def max_profit(price, k):
    n = len(price)
    if n == 0 or k == 0:
        return 0
    
    # If k >= n//2, we can make as many transactions as we want
    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
    
    # dp[i][j] = max profit using at most i transactions up to day j
    dp = [[0] * n for _ in range(k + 1)]
    
    for i in range(1, k + 1):
        max_so_far = -price[0]
        for j in range(1, n):
            dp[i][j] = max(dp[i][j-1], price[j] + max_so_far)
            max_so_far = max(max_so_far, dp[i-1][j] - price[j])
    
    return dp[k][n-1]