← How Rewards Guide Actions
Problem Medium

Expected Profit of a Newsvendor

You are a newsvendor. Each morning, before demand is known, you order q newspapers at unit cost cost. Demand is discrete: value demand[i] occurs with probability probs[i]. You sell each copy at price. Leftovers are worth salvage. Unmet demand earns nothing.

When demand realizes as d, profit is

profit(q, d) = price · min(q, d) + salvage · max(q − d, 0) − cost · q

Return the expected profit of ordering q newspapers:

E[profit] = Σ probs[i] · profit(q, demand[i])
def expected_profit(q: int, demand: List[int], probs: List[float], cost: float, price: float, salvage: float = 0.0) -> float

Example 1

Input:  q = 3
        demand = [0, 1, 2, 3, 4, 5]
        probs  = [0.05, 0.15, 0.25, 0.25, 0.20, 0.10]
        cost = 2, price = 5, salvage = 0
Output: 5.5

Walk each possible d. For d = 0 you lose 6 (contribution −0.30). For d = 3 you make 9 (contribution 2.25). Sum every world times its probability and you get 5.5.

Example 2

Input:  q = 3, demand = [3], probs = [1.0], cost = 2, price = 5, salvage = 0
Output: 9.0

Demand is certain. You buy 3, sell 3: profit = 15 − 6 = 9.

Example 3

Input:  q = 0, demand = [0, 1, 2, 3, 4, 5], probs = [0.05, 0.15, 0.25, 0.25, 0.20, 0.10], cost = 2, price = 5, salvage = 0
Output: 0.0

Ordering nothing costs nothing and sells nothing.

Constraints

01

Walk through Example 1

Pick an order quantity, then reveal demand one outcome at a time. The running expected value starts at zero and accumulates each contribution P(d) · profit(q, d) — the same sum your function has to return.

Buy cost c2
Sell price p5
Salvage s0
Critical fractile(p−c)/(p−s) = 0.60
profit(q, d) = p min(q, d) + s max(q − d, 0) − c q
Order quantity q = 3
Running expected value
0.00
Demand d P(d) Sold Left Short Profit P(d) · profit Running EV
02

Solution

CPython in the browser. Tab indents, or completes from the live kernel (Jedi). Shift+Tab dedents. ⌘/Ctrl+Enter runs the buffer. Names persist across runs until you restart.

Loading Python runtime…
Waiting for the runtime.