Memoized Fibonacci evaluation 2026-10-13
The Fibonacci numbers give an exact example. For a nonnegative integer , their recurrence relation isTo obtain by direct recursion, evaluate and separately; computing also evaluates . The full call tree has 15 occurrences but just six distinct arguments, . Shared dependencies form a Directed acyclic graph because every directed edge goes to a strictly smaller argument. Memoization evaluates a distinct argument on first demand; filling values in increasing argument order is the corresponding bottom-up dynamic programming calculation.[ref]
Lecture 15: Recursive Algorithms (6.006 Spring 2020) by Massachusetts Institute of Technology, 6.006 course staff. MIT 6.006 Spring 2020, Lecture 15: Recursive Algorithms, printed pp. 2–3, Fibonacci Numbers and Re-using Subproblem Solutions
Repeated calls for Fibonacci numbers and their shared Directed acyclic graph of dependencies
. The call tree contains 15 occurrences for . The dependency graph contains six distinct arguments and eight directed edges. Equal labels have equal colors; arrows in the right panel point from a caller to the value it requires. Details.Use an initially empty hash table
memo, shared by every recursive call. Count even the first evaluations of the two base cases, store only completed results, evaluate the left term first, and retain all entries. The following original procedure assumes a nonnegative integer argument:def cached_fib(n, memo):
if n in memo:
return memo[n]
if n < 2:
value = n
else:
value = cached_fib(n - 1, memo) + cached_fib(n - 2, memo)
memo[n] = value
return valueEvery self-call must pass through the memoization lookup. Wrapping only the outer call while leaving inner calls uncached retains the repeated work. Test membership rather than whether the stored value is nonzero: is a valid completed result.
For cold , the lookup arguments are . The first six are absent; the last three reuse completed answers. Results are stored on return in argument order , with values . Thus there are nine wrapper calls, six body evaluations and four additions. Repeating with the same table takes one wrapper call and no body evaluation. Requesting next evaluates only its body, reuses and , and stores : three wrapper calls, one body evaluation and two hits.
An exact memoization lookup trace and the effect of retaining or clearing its table
. The first row records cold lookup order. The table records successive requests with one retained table; clearing it before the final request restores the cold counts. Calls include lookups that immediately return stored values; bodies count only first evaluations. Details.The direct-call count satisfies and . Its exact solution is , as substitution into this recurrence relation verifies. With the specified memoization procedure, a cold call at evaluates distinct bodies, makes additions and makes wrapper calls. There are hits: each of the nonbase bodies issues two recursive calls, in addition to the initial call. The difference is between the number of occurrences and the number of distinct subproblems.
For a graph on vertices with all edge weights in , every minimum-weight shortest path has the smallest possible number of edges. Indeed, positivity permits a simple optimum, and a simple -edge path weighs at most for , while any path with more edges weighs at least . A breadth-first search followed by weighted dynamic programming along increasing-hop edges therefore solves the single-source problem in time. Choosing an arbitrary breadth-first tree alone is insufficient: equal-hop routes may still have different weights.
Minimum vertex cover of a tree 2026-10-31
Root a finite tree, and let be the optimum vertex cover sizes of a descendant subtree conditional on excluding or including its root. Excluding a parent forces all children to be included; including it permits either child state. These facts prove the displayed recurrences by structural induction. Empty child sums give at a leaf of a rooted tree. Evaluating in postorder traversal and taking the smaller root state gives a linear-time dynamic programming algorithm.
North-east lattice path recurrence 2026-10-18
For positive integers , the north-east lattice path recurrence isThe boundaries have only straight north-east lattice paths. The origin counts the zero-step north-east lattice path once.[ref]
Discrete Mathematics: An Open Introduction (3rd edition) by Oscar Levin. §1.2, Lattice Paths: split by the final horizontal or vertical step
Proof outline. A north-east lattice path ending at has a final step either from or from . Deleting that step gives a shorter north-east lattice path; appending it reverses the operation. The two classes are disjoint and exhaust all possibilities, so the rule of sum adds their counts. At , the arrivals from contribute , while those from contribute : altogether .
Set if either integer coordinate is negative. Then the same recurrence relation applies on the nonnegative axes away from : one predecessor contributes one, and the other contributes zero. Initialize separately; applying the recurrence relation there would incorrectly give zero.
Computing the grid once in increasing order of is dynamic programming: every entry uses two earlier entries. If a specified point is forbidden, set its count to zero, then continue the same recurrence relation at allowed points. This counts north-east lattice paths avoiding the forbidden points, provided the origin and endpoint are allowed. The last-step argument remains valid because appending a step to an allowed endpoint cannot visit any new intermediate integer lattice point.
Overlapping subproblems 2026-10-13
Overlapping subproblems occur when several parts of a calculation request the same smaller problem. Memoization can share its answer if the memoization key identifies that problem completely. For the Fibonacci numbers, both and require . In dynamic programming, the dynamic programming state plays the corresponding role of identifying a reusable continuation. Overlap explains potential savings; the recurrence relation and its base cases still need to be correct.
Pascal's rule Created 2026-10-13 Updated 2026-10-18
For an integer and any integer , Pascal's rule holds with the convention outside . The boundary values are , including . Initialize row zero separately: the recurrence relation does not require binomial coefficients with top index .[ref]
Discrete Mathematics: An Open Introduction (3rd edition) by Oscar Levin. §1.2, Recurrence relation for binomial coefficients and Pascal's Triangle: edge values and the two-parent rule
Proof by a marked element. Count the -element subsets of , marking the element as special. Those omitting are exactly the -element subsets of . From those containing , delete to obtain the -element subsets of that same smaller set; adjoining reverses this operation. The rule of sum adds these two disjoint counts. The proof includes and because the impossible class contributes zero.
For an original worked instance, choose three labels from and mark . Omitting it gives selections. Including it leaves two labels to choose from the other six, giving . Therefore . Under the bijection with north-east lattice paths to , membership of position seven says whether the final step is north: the marked-element split becomes the last-step split.
This makes Pascal's rule useful beyond an algebraic identity. A counting problem may have an obvious yes-or-no decision even when its factorial formula is obscure; splitting at that decision exposes a recurrence relation. When the smaller counts are shared between many cases, dynamic programming reuses them. The beauty of Pascal's triangle is that one local addition rule simultaneously organizes subsets, binary strings, north-east lattice paths, and the binomial theorem.
An embedding is determined by its chosen increasing sequence of positions. Accordingly, the all-subsequence embedding kernel counts pairs of embeddings, one in and one in , that spell the same subsequence. The two embeddings are distinguished even when they spell the same word as another pair. The empty word contributes exactly one pair.
Let , , and define for prefixes. When either prefix is empty, only the empty word has an embedding in both, soTo derive a dynamic programming recurrence, count pairs that do not use position of or do not use position of . Inclusion-exclusion givesThe remaining pairs use both final positions. These positions must be the final letters of the common word, so they contribute nothing if . If , deleting those two final positions is a bijection to arbitrary embedding pairs on the two shorter prefixes, including their empty pair. Their contribution is therefore . HenceEquivalently, when the final symbols agree the recurrence simplifies to ; when they differ, subtract the diagonal term. Fill the table in increasing prefix order and return . The boundary values and the disjoint counting argument prove correctness by induction on .
A one-row implementation of this dynamic programming uses the saved old diagonal entry:The assignment to
F[0..p] := 1
for i := 1 to n:
diagonal := 1
for j := 1 to p:
above := F[j]
if x[i] = y[j]:
F[j] := above + F[j-1]
else:
F[j] := above + F[j-1] - diagonal
diagonal := above
return F[p]diagonal retains the value from the previous row before F[j] was overwritten. Swapping and if necessary minimizes the row length. Thus the time complexity is arithmetic operations and the extra space complexity is integer cells. Empty inputs return one immediately.These counts include multiplicity: for , the empty word contributes , the word contributes , and contributes , giving , not three. More generally, each result is at most , since it counts some pairs of position subsets. Exact integers therefore require bits; the stated quadratic bound is an arithmetic-operation bound, with a conservative bound for elementary bit arithmetic.
The proposed positive-semidefinite kernel is valid: for each finite string only finitely many coordinates are nonzero, so is a well-defined feature map into the inner product space of finitely supported coordinate families, and its inner product is exactly .
Past exam of the computer science course of the University of Oxford 2018 Algorithms 2 c Solution 2026-10-31
Root the tree arbitrarily. For each vertex , let be the minimum vertex cover size in its descendant subtree, conditional on selecting , and the corresponding minimum conditional on omitting . Process the vertices in postorder traversal. For every child of ,At a leaf of a rooted tree, the empty sums give . Return at the root .
For algorithm correctness, if is selected, each child subtree may independently use its cheaper state, since the connecting edge is already covered by . If is omitted, each child must be selected to cover its connecting edge. Distinct child subtrees have no edges between them because the input is a tree. These observations prove the recurrences by structural induction. Each edge contributes constant work once, giving time complexity and space with adjacency lists. The single-vertex tree correctly has optimum zero. This is minimum vertex cover of a tree by dynamic programming.
Past exam of the integer programming course of the University of Oxford 2011 2 a Solution 2026-10-31
Let item have weight and profit . Define as the largest profit obtainable from the first items with capacity at most the nonnegative integer . Set . The last item is either absent or present once, giving the dynamic programming recursionThe two alternatives exhaust the feasible binary decisions. In the second alternative, deleting item leaves exactly the smaller subproblem with capacity , which proves the recurrence.
Fill rows , and within each row capacities . Store which alternative attains each maximum. Backtrack from : when exclusion was chosen, set and move to ; when inclusion was chosen, set and move to . Ties may be resolved either way. Thus the stored values yield an actual optimal selection, not just its objective value.
For items and capacity , the algorithm uses arithmetic operations and space with the full backtracking table. It is a pseudo-polynomial algorithm, since is a numerical capacity rather than its bit length. A value-only version can use one row, but must update capacities in decreasing order to avoid reusing the same item.
Use global sequence alignment, for example the Needleman-Wunsch algorithm with an appropriate substitution matrix and gap penalty. The two full-length globin proteins are related by orthology and are from closely related species, so the expected correspondence extends across both complete sequences. Unmatched ends should normally contribute to the score rather than being discarded.
With a linear gap penalty of magnitude , the dynamic programming entry is the best score for the first and residues. It satisfieswith , , and traceback from . An affine gap penalty uses separate match and gap states.
Use local sequence alignment, such as the Smith-Waterman algorithm, to compare the globin fragment with the matching region of each full-length target. A global sequence alignment would penalize long target flanks absent from the fragment. For a linear gap penalty the dynamic programming recurrence includes a restart option:Initialize boundary entries to zero, start traceback at the largest entry anywhere, and stop at zero. If the entire query is known to be valid and must be retained, fitting sequence alignment is a suitable refinement: align the whole fragment while leaving target flanks unpenalized.
First check the sequence alphabet: the prompt calls the targets “genes”. If the FASTA format file contains DNA rather than protein, translate the relevant coding sequences into amino acids before a protein-to-protein sequence alignment. If coding frames are unknown, search translated frames. A file in FASTA format specifies storage syntax, not whether the contents are nucleotides or residues.
The gain comes from avoiding a full dynamic programming table for every target. BLAST searches for short, sufficiently high-scoring word matches between query and database, then extends promising seeds. Modern versions reserve expensive gapped refinement for candidates passing earlier filters. FASTA sequence search similarly starts from short word matches, collects promising runs along alignment diagonals, and refines or joins selected regions. Word lookup and database indexing make candidate discovery inexpensive compared with considering every pair of positions.[ref]
Basic local alignment search tool by Stephen F. Altschul and others. pp. 403–406, word matches and hit extension
[ref]Improved tools for biological sequence comparison by William R. Pearson and David J. Lipman. pp. 2444–2446, FASTA search stages
These are heuristic algorithms: a good local sequence alignment can be missed if it has no acceptable seed, contains many interruptions, or is filtered before extension. Longer words and higher seed-score thresholds usually speed the search but reduce sensitivity; shorter words and looser thresholds recover weaker similarities at greater cost. Repetitive or compositionally biased regions can create many uninformative hits and erode both speed and specificity. No guarantee remains of finding the optimal sequence alignment for the chosen scoring scheme.
Use the supplied BLOSUM62 entry for every diagonal move in the Smith-Waterman algorithm, while retaining the stipulated linear gap penalty of . If and are the current amino acids, the dynamic programming recurrence isThe zero option permits a new local start. The following original implementation also records the traceback coordinates needed in part (c); its tie ordering is left, up, diagonal, and an equal overall maximum replaces the previous best cell, as in the supplied convention:
def local_alignment(query,reference,alphabet,scores,gap=-1):
lookup={aa:i for i,aa in enumerate(alphabet)}
table=np.asarray(scores,dtype=int)
height,width=len(query)+1,len(reference)+1
H=np.zeros((height,width),dtype=int)
back=np.zeros((height,width),dtype=np.int8)
best=(0,0,0)
for i,a in enumerate(query,1):
for j,b in enumerate(reference,1):
# Order implements the printed LEFT, UP, DIAGONAL tie priority.
candidates=(0,H[i,j-1]+gap,H[i-1,j]+gap,
H[i-1,j-1]+int(table[lookup[a],lookup[b]]))
value=max(candidates);H[i,j]=value
back[i,j]=0 if value==0 else candidates.index(value)
if value>=best[0]:best=(value,i,j)
score,i,j=best;query_end,ref_end=i,j
aq=[];ar=[]
while H[i,j]>0:
step=back[i,j]
if step==1:aq.append('-');ar.append(reference[j-1]);j-=1
elif step==2:aq.append(query[i-1]);ar.append('-');i-=1
elif step==3:aq.append(query[i-1]);ar.append(reference[j-1]);i-=1;j-=1
qa=''.join(reversed(aq));ra=''.join(reversed(ar));length=len(qa)
identities=sum(a==b and a!='-' for a,b in zip(qa,ra))
similarities=sum(a!='-' and b!='-' and table[lookup[a],lookup[b]]>0 for a,b in zip(qa,ra))
gaps=sum(a=='-' or b=='-' for a,b in zip(qa,ra))
return dict(query=qa,reference=ra,score=int(score),query_start=i+1,query_end=query_end,
reference_start=j+1,reference_end=ref_end,query_length=len(query),reference_length=len(reference),
alignment_length=length,identities=int(identities),similarities=int(similarities),gaps=int(gaps),
identity_percent=100*identities/length if length else 0.,
similarity_percent=100*similarities/length if length else 0.,gap_percent=100*gaps/length if length else 0.)
queries = {"baboon": baboon, "squirrel_monkey": squirrel_monkey,
"dingo": dingo, "goldfish": goldfish}
alignments = {
name: local_alignment(seq, reference_epo_receptor_human, amino_acids, bmat)
for name, seq in queries.items()
}
for name, result in alignments.items():
print(name, "score", result["score"])
print(result["query"])
print(result["reference"])The resulting local sequence alignments, with the query above the reference, are:
baboon; score 314
SLLTPSDLDPLILTLSLILVLIVVLLTVLALLSHRRALKQKIWPGIPSPESEFEGLFTTHKG-FQL
SLLTPSDLDPLILTLSLILVVILVLLTVLALLSHRRALKQKIWPGIPSPESEFEGLFTTHKGNFQLsquirrel monkey; score 278
VCFWEEAASAGMGPDNYSFSYQL-DNEPWKR-CRLHQTPTARGVVRFWCSLPRADTSS
VCFWEEAASAGVGPGNYSFSYQLED-EPWK-LCRLHQAPTARGAVRFWCSLPTADTSSdingo; score 301
MNHLW--THLWPG-VGSLCLLLAGAAWASLPKP-L-DPKFESKAALLAARAPEELLCFTERLEDLVCFWEE
MDHL-GAS-LWP-QVGSLCLLLAGAAWAP-P-PNLPDPKFESKAALLAARGPEELLCFTERLEDLVCFWEEgoldfish; score 190
L--LVLSIGLILC--L-LSLTVI-L-SHQKFLLK-KLWPDIPTPEHKFPGLFTVYKGDFKE-WMSH-NNGSM
LDPLILTLSLILVVILVL-LTVLALLSHRR-ALKQKIWPGIPSPESEFEGLFTTHKGNF-QLWL-YQNDGCLThe several short gaps are a consequence of the specified inexpensive linear gap penalty; substituting a different default or an affine gap penalty would solve a different scoring problem.
Past exam of the mathematics course of the University of Cambridge 2007 iii Paper 40 6 c Solution Created 2026-10-03 Updated 2026-10-14
Several other approaches illustrate the range between fast heuristics, certified bounds and approximation schemes.
Sorting weights in decreasing order before greedy assignment avoids the example : it starts with the weight , then places both unit weights in the other bin, giving the optimum. This is a useful scheduling heuristic, although improvement on one example is not a proof of an arbitrary claimed approximation ratio. Local improvement can additionally move a single item or swap items between bins whenever it reduces the maximum load; it produces a local optimum, which need not be global.
A linear-programming relaxation replaces by . The choice for every item gives load in both bins, and summing the load constraints shows that no smaller relaxed value is possible. Together with the indivisibility bound this provides a lower bound on the integer optimum. Any feasible heuristic schedule gives an upper bound . Their ratio is a computable quality certificate. Branch-and-bound can improve these bounds by fixing assignment variables and solving subproblems, although worst-case exact running time need not be polynomial.
For integer weights one can instead solve the problem exactly by dynamic programming. Start with attainable subset sums and updatediscarding values above . Let be the largest retained sum. Choosing that subset for one bin gives loads and maximum , which is optimal because every partition has a lighter side of weight at most . The running time is pseudopolynomial: it depends on numeric magnitude, not merely the binary length of .
This exact algorithm also yields rounded dynamic programming for two-bin load balancing. For rational weights and , choose and scaled integer weights . Their total is at most , so exact dynamic programming on them costs arithmetic operations. Let be its optimal scaled maximum load. The original optimal partition is feasible for the scaled problem with load at most , so . When the scaled partition is lifted, each bin contains at most rounding errors, each smaller than . Therefore its original maximum load satisfiesThis is a fully polynomial-time approximation scheme: for each requested tolerance it gives a certified feasible solution in time polynomial in the encoded rational input and , with rational arithmetic accounted for. It works here because two-bin balancing has the subset-sum structure; one cannot infer that arbitrary combinatorial optimization problems admit such a scheme.
Past exam of the mathematics course of the University of Cambridge 2009 iii Paper 39 2 ii Solution Created 2026-10-03 Updated 2026-10-14
Interpret the exponential distribution change time as an exogenous time independent of the stock's Brownian motion, or, equivalently for this calculation, as having constant conditional intensity while the rate remains high. Its marginal distribution alone would not imply that conditional intensity if the change time carried information about stock returns. Write , , , and let be the prechange value function.
Over a short interval , a rate change occurs with probability and changes continuation value from to . The dynamic programming equation is consequentlyThis jump term distinguishes the exponential interest-rate switch from a permanent higher bank rate.
By the homogeneity of CRRA utility, put , with . Differentiating the strictly concave expressions in and givesThe optimized consumption terms contribute , and the optimized investment terms contribute . With , the Hamilton-Jacobi-Bellman equation reduces toEquivalently,The left side is continuous and strictly increasing for , with limits zero and infinity. Thus gives one and only one positive root. This scalar equation is an explicit characterization for arbitrary real ; elementary closed forms are not generally available. For example, when ,Use until the rate changes, and afterwards. If the two rates coincide, the root is ; as tends to infinity, it also tends to .
For a direct attainability check, use the proposed prechange constant fractions. The geometric Brownian motion moment is on the prechange evolution. Conditioning on the independent exponential distribution time therefore givesThe denominator is positive because the scalar equation gives . Hence the candidate policy actually achieves the stated value.
One can also verify the upper bound for both signs of without relying on a sign-sensitive terminal-value argument. Let be the current regime, the candidate portfolio wealth, andIf and , the Itô formula and the scalar equation givewhere the jump term stops after the switch and continuous coefficients are understood predictably. Thus is a positive martingale deflator: for any admissible portfolio wealth , the process is a nonnegative local martingale. It follows thatFor the candidate policy, . Indeed its surviving prechange term decays at rate , and its postchange terms decay at rate ; integrating over the switch time preserves convergence to zero. The finite-time moment computations also make its budget equality exact. Consequently . Apply the concave supporting-tangent inequalityand integrate in time and expectation. The budget inequality proves that no admissible policy exceeds the candidate. This verifies the value function, including when .
Both and are needed for a finite prechange answer. If the postchange value is already infinite, that problem persists after the almost surely finite switch. If but , then for a small constant prechange consumption fraction makes the expected utility function before the switch diverge, or makes its supremum diverge when . For , the optimal no-consumption terminal moment before the switch is ; withdrawals only increase this negative-power moment. The expected magnitude of the negative postchange continuation utility function therefore contains the divergent integral . Thus these cases yield respectively or , rather than a positive-root solution.
Past exam of the mathematics course of the University of Cambridge 2013 iii Paper 40 1 Solution Created 2026-10-03 Updated 2026-10-07
Wealth and admissibility. The dollar holding earns the risky return, while earns the continuous-time bank account return. Removing consumption therefore givesHere is a dollar amount, not a number of shares; the number of shares is . Both controls must use available information: take predictable and progressively measurable, withalmost surely on every finite interval. Require a well-defined objective and an admissible trading strategy satisfying . At zero portfolio wealth this excludes continued risky gambling or positive consumption. The state-price budget constraint rules out doubling strategies. Throughout the diffusion calculations take , positive discount , positive decay , and finite value; degeneracies are discussed where they affect the conclusions.
Satisfaction and dynamic programming. Write the consumption satisfaction stock asThe product rule gives, almost everywhere in time,This state is a finite-variation process, so it has no quadratic covariation with portfolio wealth. Applying the Itô formula to the discounted value function over a short interval, then using dynamic programming, gives the interior HJB equationAssuming , completing the square givesThe last supremum is zero if and infinite otherwise. Thus the gradient constraint for unbounded consumption is , and wherever the inequality is strict. Since there is no direct penalty for a very large consumption rate, an active boundary can involve singular consumption control. In that relaxed interpretation the HJB equation isWith ordinary rate controls, this describes the supremum and its limiting transfer policy; it does not promise that an instantaneous transfer is attained by a finite rate.
Power reduction. An additive constant in the utility function only adds a control-independent constant divided by to the value, so normalize . Put and for . Scaling portfolio wealth, consumption satisfaction and the controls by the same positive number gives the wealth-to-satisfaction reductionConsequently the reduced HJB equation isIn the strict waiting region the first expression vanishes and consumption is zero. On a transfer region the second vanishes; integrating it gives . This reflects preservation of during an instantaneous wealth-to-satisfaction transfer.
Why a waiting threshold is expected, and its qualification. The gradient constraint for unbounded consumption compares the benefit of increasing consumption satisfaction with the opportunity cost of spending financial portfolio wealth. When consumption satisfaction is already large relative to cash, waiting lets consumption satisfaction decay while financial portfolio wealth earns returns; consuming immediately can be wasteful. Homogeneity makes the comparison depend only on . For fixed , joint concavity of the value function makes concave in financial portfolio wealth . It is nondecreasing because an immediate transfer can reproduce any smaller financial allocation. Consequently its derivative is nonnegative and nonincreasing in : a strict waiting region, if present, starts at zero financial portfolio wealth and ends at a single transfer boundary. Homogeneity makes the corresponding boundary a ratio . In the usual finite-boundary regime this gives for , and transfers push a larger ratio down towards . The condition is a comparison of marginal values, not the ordinary formula : current utility function here depends on consumption satisfaction, not on current consumption.
A positive threshold is not guaranteed by the printed hypotheses alone. A useful sufficient local test illustrates the intended argument. Let . At zero portfolio wealth,Starting with a small extra portfolio wealth , holding it in the continuous-time bank account until a fixed time , then transferring it into consumption satisfaction, has right derivative in at zero equal toTherefore, if , the portfolio wealth marginal value is strictly larger than the consumption satisfaction marginal value at zero. With the usual continuity of marginal values, there is a positive interval on which the gradient constraint for unbounded consumption is strict. The fixed-total-resource concavity argument then gives the threshold structure.
For a concrete counterexample to an unconditional positive threshold, take , , , and . There is zero market price of risk. The relaxed value isIndeed , , and the optimized waiting residual, after division by , isbecause and the integrand is decreasing. The Itô formula gives an upper bound by , while transferring all portfolio wealth into consumption satisfaction over intervals tending to zero attains that bound in the limit. Hence the transfer boundary is in this example. The positive-threshold explanation needs a parameter regime supporting a genuine waiting region. For , even the zero-wealth value is finite only if ; otherwise decaying consumption satisfaction gives value .
Past exam of the mathematics course of the University of Cambridge 2013 iii Paper 40 2 Solution Created 2026-10-03 Updated 2026-10-07
The joint generator. With again measured in dollars, portfolio wealth obeysIts noise and the factor noise are driven by the same Brownian motion. Their quadratic covariation is , so the diffusion generator has a cross derivative. Dynamic programming and the Itô formula giveAll coefficient functions in this formula are evaluated at . The cross derivative is essential: it gives intertemporal hedging demand. Normalizing CRRA utility as , where , the two optimizations give, at nonzero volatility,and henceHere .
Homogeneity and the reduced equation. Scaling initial portfolio wealth and both controls preserves the portfolio wealth constraint and multiplies the objective by the positive number . ThusThis expression is valid for both signs of : is negative when , but its portfolio wealth derivative is positive. Its derivatives areSubstitution yieldsThe resulting feedback isThe first portfolio term is myopic, and the second is intertemporal hedging demand.
Constant market price of risk. If and volatility is nonzero, the portfolio term becomes , so the magnitude of stock volatility disappears. Applying the power transformation of a complete-market investment equation cancels the squared-gradient terms and gives the further reductionFor its economic solution is . ThusTo see why this solves the investment-consumption problem, optimize directly over Brownian portfolio exposures, writing . The portfolio wealth equation becomes , which no longer contains . With nonzero volatility the same admissible exposure processes are available for every factor state, so the attainable wealth-consumption pairs, and therefore the value, are exactly those of the Merton consumption-investment problem. This also excludes extraneous solutions of the linear equation without imposing artificial factor boundary data.
The printed boundedness assumptions do not ensure nonzero volatility or a finite value. The unsimplified HJB equation remains the correct control equation at a zero of . There the hedge term vanishes; if , the riskless excess return gives arbitrage with unrestricted holdings. Under , a zero-volatility state offers only the bank exposure at that instant. For example , satisfies this relation for any chosen , but its value uses , not a fictitious nonzero risk premium. The constant-value formula using presupposes access to the Brownian exposure, with sufficient integrability for the corresponding holdings. Additive utility constants again only shift by a constant divided by .
Past exam of the mathematics course of the University of Cambridge 2013 iii Paper 40 3 Solution Created 2026-10-03 Updated 2026-10-07
Available portfolio wealth and the ruin boundary. Put , the constant interest payment on the fixed loan. The loan principal is already included in available portfolio wealth; it is not a growing portfolio holding. ThereforeIn particular the interest outflow is , not . Writing would instead give net portfolio wealth drift , which explains the distinction.
Let denote the ruin time, to avoid confusing it with a fixed terminal horizon. The objective stops at ; consequently the absorbing boundary is , without an obligation to keep financing the loan after ruin. Dynamic programming gives, for ,For increasing strictly concave value, put and use inverse marginal utility . The optimal controls and the optimized HJB equation arewhere . For CRRA utility with , write and . Then
Dualization and the printed constant. Use the convex wealth-variable Legendre dualAt an interior maximizing portfolio wealth, , and . The dual HJB equation is the linear Euler differential equationA trial power givesDirect substitution givesThe PDF prints an additional factor before in its definition of . That printed definition is inconsistent with its own identity for . The expression above is the one used here; assume this corrected .
Solution when . Assume positive discount , nonzero , and . Let and be the two roots of :Since , . Put . For , the general interior solution isThe appropriate large-wealth condition is the Merton consumption-investment problem boundIndeed any original control consumes in the debt-free comparison model until ruin, and . Dualizing this bound gives . Because , convexity and this upper bound force as .
At the other endpoint portfolio wealth reaches zero. If , the dual ruin boundary with debt service requiresSolving these two equations givesFor , , and for , , so the quantity defining is positive in either case. These formulas determine the entire value. For each , choose the unique satisfyingThenBoth terms in the bracket are positive, even when and . Thus , decreases from infinity to zero as increases, and the portfolio wealth inversion really is unique. The extended dual is continuously differentiable and convex.
There is no additional condition . In factAvailable portfolio wealth is killed at zero; the portfolio can have a nonzero limiting volatility immediately before ruin. Imposing a reflecting-boundary or zero-curvature condition would solve a different problem.
For , the linear forcing resonates with the root . Put . The dual and boundary constants instead areExtend by zero for . Hereand the controls remain and , with .
Verification and transversality. The candidate is nonnegative, increasing, strictly concave and zero at ruin. Its HJB equation makes the discounted value plus accrued utility a local supermartingale for every admissible control, and a local martingale for the stated feedback. Localization at positive lower and finite upper portfolio wealth levels gives the finite-horizon comparison. The investment value transversality condition follows from the same debt-free bound: applying the Itô formula to and maximizing its risky term givesThe nonnegative consumption and debt-service drifts only decrease this bound. Thus the expected terminal candidate tends to zero. The feedback has at most linear growth, including a finite limit as portfolio wealth decreases to zero; stopping it at ruin gives an admissible policy. Letting localization levels and then the horizon tend to their limits proves that the candidate is the value, rather than just a formal dual solution. If , the absorbing-debt boundary disappears and the ordinary Merton consumption-investment problem formula is recovered.
Zero market price of risk. With and , the dual equation is first order. If , the preceding formulas remain valid with for , and the logarithmic formula with for ; there is no term and . The same boundary and transversality argument verifies this deterministic consumption policy.
The remaining finite-value case has and . Put , andThe correct convex dual and its corresponding value areThe two value branches have the same value and derivative at . Above , hold no stock and consume ; the surplus over grows at rate . If , the lower branch is attained by zero stock holding and constant consumption : portfolio wealth solves until ruin, and direct integration gives .
If and , the lower branch is a supremum attained in a limit of increasingly rapid fair stock lotteries between zero and , followed by the upper-branch policy on success. The success probability tends to and the fixed service cost during the lottery tends to zero. This is possible because unrestricted dollar holdings in the nonzero-volatility stock produce a fair Brownian motion exposure even when its excess drift is zero. The supporting linear branch has optimized waiting residual ; the fast lotteries, rather than a finite feedback optimizer, supply the missing control limit. The piecewise candidate is concave, has nonpositive waiting residual everywhere, and the preceding moment bound still supplies an upper-bound verification. This degenerate case can have a supremum without an ordinary maximizing strategy.
Past exam of the mathematics course of the University of Cambridge 2015 ii Paper 3 25K Solution Created 2026-09-24 Updated 2026-10-06
Assume nonnegative wealth and rewards, and initially . Set , and let take the values with equal probability conditional on not being caught. For the retirement threshold with multiplicative capture risk, the dynamic programming equation is the displayed maximum; capture contributes zero. Write .
Inductively, if , all future successful wealth levels also lie above , so . Continuing in town is then worth , and retirement is optimal. If , choose with . Continuing for just one night and then retiring is worth , so immediate retirement cannot be optimal for any . This proves an optimal policy continues exactly when , with retirement chosen at the threshold.
Now suppose and . Since also , town has the larger threshold, so . The functions are nondecreasing in wealth and in , and ; these properties follow by induction from the dynamic programming equation.
Prove by induction on the remaining horizon that town is never optimal when continuation is worthwhile. For , the difference between the town values is . If , monotonicity giveswith strictness because the first bracket is positive under the hypotheses.
For , first suppose . The second town's successful large-reward branch retires, so its value is . Town is worth at least . Their difference is at leastIf instead , all states after either first-night reward remain below the threshold. By induction a policy starting in town then chooses town on its second night. Its value isInterchanging the first two towns gives exactly the same value, because capture probabilities multiply and independent rewards add. After starting in town , however, the induction hypothesis says town is strictly inferior on the second night at every possible surviving wealth level. Replacing that second choice by the optimal one strictly improves the value. This proves town dominates throughout every finite horizon.
Past exam of the mathematics course of the University of Cambridge 2015 ii Paper 4 25K Solution Created 2026-09-24 Updated 2026-10-06
Treat the white noise as innovations with conditional mean zero and conditional second moment , independent of the chosen past control. This is the convention needed for the dynamic programming calculation. The printed stage cost is , not one-half of both terms.
With terminal value , induction in the Bellman equation givesIf , completing the square yieldsThus for every horizon, in particular . The same completion gives the average-cost Bellman equation solution , up to an additive constant in .
For every policy in , conditional second moments satisfy . Iterating givesThe Bellman inequality implies . Dividing by and using the bound proves that every admissible policy has lower limiting average cost at least , even if its ordinary limit does not exist. The feedback belongs to because . It makes the Bellman inequality an equality, and its bounded terminal second moment proves its average cost tends to . Therefore it is optimal over .
Merely uncorrelated noise with the displayed unconditional moments would not ensure the conditional identities for arbitrary adapted controls. The innovation interpretation specifies the hypothesis used in the calculation.

