```python
import math

def max_profit(price, k):
    """
    Calculates the maximum profit from at most k stock transactions.
    """
    num_days = len(price)

    if k == 0 or num_days < 2:
        return 0

    # Optimization: If k is large enough, we can transact as many times as we want.
    # This simplifies the problem to summing up all positive price differences.
    if k >= num_days // 2:
        total_profit = 0
        for i in range(1, num_days):
            if price[i] > price[i - 1]:
                total_profit += price[i] - price[i - 1]
        return total_profit

    # profits_after_sell[j]: max profit with at most j transactions, not holding a stock
    # profits_after_buy[j]: max profit with at most j transactions, holding a stock
    profits_after_sell = [0] * (k + 1)
    profits_after_buy = [-math.inf] * (k + 1)

    for current_price in price:
        # Iterate backwards to use the profits_after_sell[j-1] from the previous day
        for j in range(k, 0, -1):
            # The max profit if we end today with no stock is either:
            # 1. The same as yesterday with no stock (profits_after_sell[j]).
            # 2. We sell the stock we held yesterday (profits_after_buy[j] + current_price).
            profits_after_sell[j] = max(profits_after_sell[j], profits_after_buy[j] + current_price)

            # The max profit if we end today holding a stock is either:
            # 1. The same as yesterday holding a stock (profits_after_buy[j]).
            # 2. We buy a stock today, having had no stock yesterday after j-1 transactions
            #    (profits_after_sell[j - 1] - current_price).
            profits_after_buy[j] = max(profits_after_buy[j], profits_after_sell[j - 1] - current_price)

    return profits_after_sell[k]
```