donnemartin/interactive-coding-challenges · error · ValueError

prices must have at least two values

Error message

prices must have at least two values

What it means

Raised by Solution.find_max_profit when the prices list has fewer than 2 entries; a single price gives no buy/sell pair, so max profit is undefined. It is a defensive ValueError guard at the top of the method. The algorithm then pops the first element as the initial min price and iterates the rest.

Source

Thrown at online_judges/max_profit/max_profit_solution.ipynb:105

    "## Code"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "\n",
    "\n",
    "class Solution(object):\n",
    "\n",
    "    def find_max_profit(self, prices):\n",
    "        if prices is None:\n",
    "            raise TypeError('prices cannot be None')\n",
    "        if len(prices) < 2:\n",
    "            raise ValueError('prices must have at least two values')\n",
    "        min_price = prices.pop(0)\n",
    "        max_profit = prices[0] - min_price\n",
    "        for price in prices:\n",
    "            profit = price - min_price\n",
    "            min_price = min(price, min_price)\n",
    "            max_profit = max(profit, max_profit)\n",
    "        return max_profit"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Unit Test"
   ]
  },
  {
   "cell_type": "code",

View on GitHub (pinned to 358f2cc604)

Solutions

  1. Ensure the caller passes at least two prices before invoking find_max_profit.
  2. If a 0 profit is the desired behavior for <2 prices, catch the ValueError or check len(prices) >= 2 first and short-circuit to 0.
  3. Pass a copy (list(prices)) since the method pops from the input list.

Example fix

# before
profit = Solution().find_max_profit([7])  # ValueError

# after
prices = [7]
profit = Solution().find_max_profit(prices) if len(prices) >= 2 else 0
Defensive patterns

Strategy: validation

Validate before calling

if not isinstance(prices, (list, tuple)) or len(prices) < 2:
    raise ValueError('need at least two prices')
profit = Solution().find_max_profit(list(prices))

Type guard

def has_two_prices(p):
    return isinstance(p, list) and len(p) >= 2

Try / catch

try:
    profit = s.find_max_profit(prices)
except ValueError as e:
    profit = 0  # or log and skip

Prevention

When it happens

Trigger: Calling find_max_profit with a list of length 0 or 1, e.g. find_max_profit([5]) or find_max_profit([]).

Common situations: Passing an empty dataset from a file/API feed, or a test case that assumed a single price should return 0. Also note the method mutates its input via prices.pop(0).

Related errors


AI-assisted analysis of donnemartin/interactive-coding-challenges@358f2cc604 (2026-08-28). Data as JSON: /api/errors/8d92574c3469930d. Report an issue: GitHub.