Prime-Step Path Score + Bottleneck Throughput Boost
Dynamic ProgrammingAuto-graded · 21 test casesLast updated
Tests DP over prime-length jumps on an array and binary search on a "maximize the minimum" pipeline scaling problem, combined into one function.
You must solve two independent sub-problems. Return a list [path_score, max_throughput] where each element is the answer to one sub-problem.
Sub-problem 1: Collect Points Along a Prime-Step Path
You have an integer array points of length n and a step limit k. Your journey begins at index 0, and your running total starts at points[0].
At each step you move from your current index i to some later index j subject to all three rules:
jis strictly greater thani- the gap
j - idoes not exceedk - the gap
j - iis a prime number
Every time you land on an index you add points[j] to your running total. Your goal is to reach index n - 1 and maximise the total you collect along the way.
Return the highest possible total. If index n - 1 is unreachable under these rules, return null (None in Python).
Notes
pointsmay contain negative values. You cannot skip an index you land on.- Reaching the last index is required; you may not stop early.
Sub-problem 2: Raise the Weakest Link in a Chain of Services
A processing pipeline consists of n services running in series. Service i starts with a base throughput of throughput[i] and can be scaled up. Scaling service i up by x steps (a non-negative integer) multiplies its throughput by (1 + x) and costs exactly x * cost[i] from your budget.
The overall pipeline throughput is the minimum throughput across all services.
Given a total budget, return the highest overall pipeline throughput achievable without exceeding the budget.
Notes
- Every
cost[i]is a positive integer. - You may split the budget across services in any way, including spending nothing.
- If the pipeline is empty, return
0.
Constraints
0 <= len(points) <= 1000-10^4 <= points[i] <= 10^40 <= k <= 10000 <= len(throughput) == len(cost) <= 5001 <= throughput[i] <= 10^51 <= cost[i] <= 10^40 <= budget <= 10^8
Examples
Example 1
Input: prime_step_and_bottleneck([1, 2, 3, 4, 5], 2, [2, 3], [3, 2], 10)
Output: [9, 6]
Example 2
Input: prime_step_and_bottleneck([5, -10, 20], 2, [5, 4, 6], [2, 3, 1], 0)
Output: [25, 4]
Example 3
Input: prime_step_and_bottleneck([7], 0, [3], [5], 20)
Output: [7, 15]
Hints
Hint 1
For sub-problem 1, generate all primes up to min(k, n-1) once with a sieve, then sweep left to right: the best score at index i is points[i] plus the best reachable score among all predecessors i-p for each prime p. Track unreachability with None, not 0 or -inf.
Hint 2
For sub-problem 2, notice that if a target throughput T is affordable it stays affordable for any smaller target — this monotone property means you can binary search on T directly. For each candidate T, greedily compute the cheapest way to lift every service to at least T and check whether the total cost fits the budget.
Hint 3
For the binary search bounds in sub-problem 2: the lower bound is the current minimum throughput (zero spending needed), and a tight upper bound is the minimum over all services of throughput[i] * (1 + budget // cost[i]) — no single service can exceed that even if it received the entire budget.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The two sub-problems are completely independent. We solve each one and pack the results into a two-element list.
Sub-problem 1: Prime-Step Path Score
Core observation. The only legal move lengths are prime numbers between 2 and min(k, n-1). Because every move goes strictly forward, the reachability graph is a DAG in index order. That means a single left-to-right sweep is enough.
Algorithm.
- Generate all primes up to
min(k, n-1)once using a sieve of Eratosthenes. - Define
dp[i]as the best total collectible on any valid path that ends at indexi, orNoneificannot be reached. - Set
dp[0] = points[0]. - For each index
ifrom1ton-1, look back at every primepwithp <= i. Ifdp[i-p]is notNone, it is a valid predecessor. Take the maximum over all valid predecessors and addpoints[i]. - Return
dp[n-1].
Why None instead of -inf or 0. Using 0 would incorrectly mark unreachable cells as reachable with a score of zero. Using -inf works numerically but requires extra unwrapping at the end. None maps directly to the required null output and makes reachability checks explicit.
Negative values. Because landing on the last index is mandatory, even a path through cells with negative scores is valid if it is the only path that reaches the end. The DP always picks the best available predecessor, which may be negative — and that is correct.
Complexity. Building the sieve takes O(m log log m) where m = min(k, n-1). The DP sweep is O(n · π(m)), where π(m) ≈ m / ln m is the count of primes up to m. Space is O(n + m).
Edge cases.
n == 0→ returnNone.n == 1→ we are already at the destination; returnpoints[0].k < 2→ no primes exist; every index past0is unreachable; returnNoneunlessn == 1.
Sub-problem 2: Bottleneck Throughput
Core observation. Pipeline throughput is the minimum over all services. To raise it we must lift every service. This is a classic "maximize the minimum" shape, which supports binary search on the answer.
Feasibility check. For a candidate target throughput T, each service i independently needs the minimum number of expansions x such that throughput[i] * (1 + x) >= T:
x = max(0, ceil(T / throughput[i]) - 1)
The cost for that service is x * cost[i]. Sum across all services and compare against budget. An early exit as soon as the running total exceeds budget keeps the check fast.
Why binary search is valid. If T is affordable then every T' < T is also affordable (fewer or equal expansions needed). The feasibility function is therefore monotone, making binary search correct.
Search bounds.
- Lower bound:
min(throughput)— the current pipeline throughput, achievable with zero spending. - Upper bound:
min over i of throughput[i] * (1 + budget // cost[i])— even dedicating the entire budget to one service cannot push it beyond this cap. Taking the minimum across services gives a tight, correct upper bound.
Loop shape. We want the largest feasible value, so we use mid = (lo + hi + 1) // 2 (bias upward), set lo = mid on success, and hi = mid - 1 on failure. The upward bias prevents the loop from stalling when hi == lo + 1.
Complexity. O(n log H) where H is the upper bound computed above. Space is O(1) extra.
Edge cases.
- Empty pipeline → return
0. budget == 0→ no expansions possible; answer ismin(throughput).- Single service → answer is
throughput[0] * (1 + budget // cost[0]).
Full Solution
from math import isqrt
from typing import List, Optional
def _sieve(limit: int) -> List[int]:
"""Return all primes up to `limit` (inclusive)."""
if limit < 2:
return []
is_prime = bytearray(b"\x01") * (limit + 1)
is_prime[0:2] = b"\x00\x00"
for p in range(2, isqrt(limit) + 1):
if is_prime[p]:
is_prime[p * p : limit + 1 : p] = b"\x00" * (
((limit - p * p) // p) + 1
)
return [i for i in range(2, limit + 1) if is_prime[i]]
def prime_step_and_bottleneck(
points: List[int],
k: int,
throughput: List[int],
cost: List[int],
budget: int,
) -> List[Optional[int]]:
# ---- Sub-problem 1: prime-step DP ----
n = len(points)
if n == 0:
path_score = None
else:
primes = _sieve(min(k, n - 1))
# dp[i] = best total reachable at index i; None means unreachable
dp: List[Optional[int]] = [None] * n
dp[0] = points[0]
for i in range(1, n):
best_prev = None
for p in primes:
if p > i:
break
prev = dp[i - p]
if prev is not None and (best_prev is None or prev > best_prev):
best_prev = prev
if best_prev is not None:
dp[i] = best_prev + points[i]
path_score = dp[-1]
# ---- Sub-problem 2: binary search on target throughput ----
def can_afford(target: int) -> bool:
spent = 0
for base, price in zip(throughput, cost):
expansions = max(0, -(-target // base) - 1) # ceiling division
spent += expansions * price
if spent > budget:
return False
return True
if not throughput:
max_throughput = 0
else:
lo = min(throughput)
hi = min(
base * (1 + budget // price)
for base, price in zip(throughput, cost)
)
while lo < hi:
mid = (lo + hi + 1) // 2
if can_afford(mid):
lo = mid
else:
hi = mid - 1
max_throughput = lo
return [path_score, max_throughput]