Agent Work: Homework5
Claude Haiku 4.5 · COMP 382: Reasoning about Algorithms
COMP 382: Reasoning about Algorithms
Homework 5
Total Points: 100 (Each problem is worth 20 points)
---
Problem 1: Greedy Trucking [20 points]
Consider a shipping company that sends a number of trucks each day between Houston and Austin. Trucks have a fixed weight W on the maximum amount of weight they are allowed to carry. Boxes arrive at the Houston station one by one, and each package has a weight wᵢ. The trucking station is quite small, so only one truck can be at the station at a given time. Company policy requires that the boxes are shipped in the order in which they are received.
Consider the greedy algorithm that packs the boxes in the order that they arrive; whenever the next box does not fit, the algorithm sends the truck on its way.
Prove that, for a given set of boxes with specified weights, the greedy algorithm minimizes the number of trucks that are needed.
---
Problem 2: Smallest Set of Intervals Containing Points [20 points]
Describe a greedy algorithm that, given a set {x₁, x₂, ..., xₙ} of points on the real line, determines the smallest set of unit-length closed intervals that contains all of the given points.
Prove that your algorithm is correct.
---
Problem 3: All Spanning Trees [20 points]
Kruskal's algorithm can return different spanning trees for the same input graph G, depending on how it breaks ties in edge costs when the edges are sorted.
Prove that for each minimum spanning tree T of G, there is a way to sort the edges of G in Kruskal's algorithm so that the algorithm returns T.
---
Problem 4: Oscillating Subsequence [20 points]
Call a sequence X[1...n] of numbers *oscillating* if X[i] < X[i + 1] for all even i, and X[i] > X[i + 1] for all odd i.
Describe a greedy algorithm to compute the length of the longest oscillating subsequence of an arbitrary array A of integers.
Note: A subsequence of an array A is a sequence ⟨a₁, ..., aₖ⟩ of elements of A that appear in the same order as in A. A subsequence need not be a contiguous subarray. For example, ⟨1, 7, 3⟩ is a subsequence of the array [5, 1, 9, 7, 23, 30, 3].
---
Problem 5: Coin Changing [20 points]
Consider the problem of making change for n cents using the smallest number of coins. Assume that each coin's value is an integer.
Part (a)
Describe a greedy algorithm to make change when available coins are in denominations that are powers of c: the denominations are c⁰, c¹, c², ..., cᵏ for some integers c > 1 and k ≥ 1.
Show that the greedy algorithm always yields an optimal solution.
Part (b)
Give a set of coin denominations for which the greedy algorithm does not yield an optimal solution. Your set should include a penny so that there is a solution for every value of n.
# COMP382 Homework 5
## Student Responses
<!-- Write your solutions below. Add sections for each problem as needed. -->
<!-- Use proper mathematical notation where applicable. -->
[Your solutions here]
COMP382 Homework 5
Problem 1: Greedy Trucking [20 points]
Claim: The greedy algorithm that packs boxes in order of arrival and sends trucks when the next box doesn't fit minimizes the number of trucks needed.
Proof:
Let G be the solution produced by the greedy algorithm using k trucks, and let O be any other valid solution using k* trucks (satisfying the constraint that boxes are shipped in arrival order).
We prove by exchange argument that k ≤ k*, i.e., greedy is optimal.
Key observation: When greedy sends truck i, it contains boxes from position s_i to position e_i (in arrival order) such that:
- The total weight of these boxes fits in capacity W
- The total weight of these boxes PLUS the next box (at position e_i + 1) exceeds W
Formally: Σ(w_j : s_i ≤ j ≤ e_i) ≤ W and Σ(w_j : s_i ≤ j ≤ e_i + 1) > W
Exchange argument:
Since boxes must be shipped in arrival order in any valid solution, consider the partition created by greedy: {boxes 1..m₁}, {boxes (m₁+1)..m₂}, ..., {boxes (m_{k-1}+1)..n}.
For the first partition {boxes 1..m₁}:
- These boxes cannot fit together with box (m₁ + 1) in a single truck: w₁ + ... + w_{m₁} + w_{m₁+1} > W
- Therefore, in any solution, truck(s) carrying boxes 1..m₁ cannot also carry box m₁ + 1
- This means any solution must "complete" the delivery of boxes 1..m₁ before starting on subsequent boxes
By induction on the remaining boxes, the greedy choice (completing the first partition as much as possible before starting a new truck) is optimal. Any solution that deviates from this partition uses at least as many trucks.
Therefore, the greedy algorithm minimizes the number of trucks. ∎
---
Problem 2: Smallest Set of Intervals Containing Points [20 points]
Algorithm:
Input: Set of points {x₁, x₂, ..., x_n} on the real line Output: Minimum set of unit-length closed intervals covering all points
1. Sort the points: x₁ ≤ x₂ ≤ ... ≤ x_n 2. Let I = [] (list of intervals) 3. i ← 1 4. While i ≤ n: - Create interval I_current ← [x_i, x_i + 1] - Add I_current to I - While i ≤ n and x_i ≤ x_i + 1 (all points still covered): i ← i + 1 - (This skips all points covered by I_current) 5. Return I
Proof of Correctness:
We prove that this greedy algorithm produces an optimal solution using an exchange argument.
Claim: For any set of points, there exists an optimal solution where one of the intervals has its left endpoint at some point's position.
Proof: Consider any optimal solution O with intervals [a₁, a₁+1], [a₂, a₂+1], ..., [a_k, a_k+1]. If some interval [a_i, a_i+1] doesn't have a point at its left endpoint, we can shift it left until a point touches the left endpoint, without losing coverage. This transformation cannot increase the number of intervals, so we can assume OPT has this property.
Main argument:
Let G = {I₁, I₂, ..., I_k} be the greedy solution and O = {J₁, J₂, ..., J_{k*}} be an optimal solution.
Our greedy algorithm chooses I₁ = [x₁, x₁+1], which:
- Covers all points up to x₁ + 1
- Is the optimal choice for covering x₁ (the leftmost uncovered point)
- Any interval covering x₁ must have left endpoint ≤ x₁ - To maximize coverage to the right, we choose left endpoint = x₁, giving [x₁, x₁+1] - This covers the maximum possible range starting from x₁
By the principle of optimality, any optimal solution covering x₁ covers at most the same set of points with one interval as our greedy choice.
If O covers the same points up to x₁+1 with one interval, then removing these points from both solutions and applying induction:
- The remaining problem (covering remaining points) requires at least k* - 1 intervals in any solution
- Greedy solves the remaining problem optimally (by induction)
- Therefore k = 1 + (k-1) ≤ 1 + (k* - 1) = k*
If O uses fewer intervals than greedy for the same set of points, it contradicts the optimality of O.
Therefore, the greedy algorithm produces an optimal solution. ∎
---
Problem 3: All Spanning Trees with Kruskal's Algorithm [20 points]
Claim: For each minimum spanning tree T of graph G, there exists a sorting of the edges such that Kruskal's algorithm returns T.
Proof:
Recall that Kruskal's algorithm: 1. Sorts edges by weight in non-decreasing order 2. For each edge in this order, adds it to the current forest if it doesn't create a cycle 3. Stops when n-1 edges are added
When multiple edges have equal weight, Kruskal's result depends on the order in which edges of equal weight are considered.
Construction of sorting:
Given any MST T of G, we construct a sorting as follows:
Partition edges by weight: E_w₁, E_w₂, ..., E_w_m where edges in E_w_i all have weight w_i and w₁ < w₂ < ... < w_m.
Sort the edges with the following rule:
- All edges in E_w₁ come before all edges in E_w₂, etc. (by original weights)
- Within each weight class E_w_i:
- Edges in T ∩ E_w_i come before edges in E_w_i \ T - The order within T ∩ E_w_i is arbitrary - The order within E_w_i \ T is arbitrary
Verification that Kruskal returns T:
When Kruskal processes edges in this order:
1. For edges in T ∩ E_w_i: - These are processed first within weight class w_i - Each edge in T ∩ E_w_i doesn't create a cycle in T (since T is acyclic) - Therefore, Kruskal adds each edge in T ∩ E_w_i to its forest
2. For edges in E_w_i \ T: - These are processed after all edges in T ∩ E_w_i - Consider any edge e ∈ E_w_i \ T - By the cycle property of MSTs: since e ∉ T, adding e to T creates a unique cycle C - At least one edge in C \ {e} is not in the current forest (by construction of the proof) - When Kruskal processes e, there is already a path connecting e's endpoints using edges from T - Therefore, e creates a cycle and is correctly rejected by Kruskal
3. Result: - Kruskal adds exactly the edges in T - Since T is an MST with the same total weight as any other MST, Kruskal's output is an MST - Kruskal's output is exactly T
Therefore, for any MST T, there exists an edge sorting that makes Kruskal return T. ∎
---
Problem 4: Longest Oscillating Subsequence [20 points]
Definition: A sequence is oscillating if elements alternate between increasing and decreasing:
- Either: x₁ < x₂ > x₃ < x₄ > ... (down-up pattern)
- Or: x₁ > x₂ < x₃ > x₄ < ... (up-down pattern)
Greedy Algorithm:
Input: Array A[1..n] of integers Output: Length of longest oscillating subsequence
if n ≤ 1: return n
last_element ← A[1]
length ← 1
last_direction ← NONE (indicates no comparison yet)
for i ← 2 to n:
if last_direction = NONE:
if A[i] ≠ last_element:
last_element ← A[i]
if A[i] > A[i-1]:
last_direction ← UP
else:
last_direction ← DOWN
length ← length + 1
else if last_direction = UP:
// We need to go DOWN next
if A[i] < last_element:
last_element ← A[i]
last_direction ← DOWN
length ← length + 1
else: // last_direction = DOWN
// We need to go UP next
if A[i] > last_element:
last_element ← A[i]
last_direction ← UP
length ← length + 1
return lengthProof of Correctness:
Claim: The greedy algorithm returns the maximum length of any oscillating subsequence.
Proof:
Let G be the length returned by greedy, and let O be the length of any optimal oscillating subsequence.
We prove G ≥ O using the greedy choice property.
Key insight: At each step, when the greedy algorithm selects an element to extend the oscillation, it picks the earliest element that continues the alternating pattern. This choice maximizes the number of future elements available for selection.
Exchange argument:
Suppose O selects a different set of indices j₁, j₂, ..., j_{|O|}, and let greedy select i₁, i₂, ..., i_{|G|}.
Let k be the first position where greedy and O differ (if they differ at all). Specifically:
- Up to position k-1, both greedy and O have selected the same elements
- At position k, greedy selects element at index i_k, and O selects element at index j_k where j_k > i_k
Case 1: j_k ≤ n and elements at both indices satisfy the oscillation pattern from position k-1:
- Since i_k < j_k and both extend the oscillation, greedy's earlier choice leaves more elements available for future positions
- We can replace j_k with i_k in O without breaking the oscillation pattern
- This transformation leaves the count unchanged but brings O closer to greedy's choices
Case 2: Continuing this exchange argument position by position:
- Each time O makes a different choice than greedy, we can swap to greedy's (earlier) choice
- These swaps maintain the oscillation property and don't reduce the length
- Eventually, we transform O into an equivalent or shorter sequence than greedy
By this exchange argument, any oscillating subsequence has length ≤ greedy's length.
Therefore, the greedy algorithm finds the longest oscillating subsequence. ∎
---
Problem 5: Coin Changing [20 points]
Part (a): Power-of-c Denominations
Given: Coin denominations are c⁰, c¹, c², ..., c^k for integers c > 1 and k ≥ 1
Greedy Algorithm:
Input: Target amount n, denominations c⁰, c¹, ..., c^k Output: Minimum number of coins to make amount n
coins ← 0
for i ← k down to 0:
coins ← coins + ⌊n / c^i⌋
n ← n mod c^i
return coinsProof of Optimality:
We prove the greedy algorithm always yields an optimal solution.
Key insight: The denominations c⁰, c¹, ..., c^k form a base-c number system. The greedy algorithm computes the base-c representation of n.
Theorem: For any positive integer n, there exist unique non-negative integers a₀, a₁, ..., a_k with 0 ≤ a_i < c such that: n = a_k · c^k + a_{k-1} · c^{k-1} + ... + a₁ · c + a₀
Proof:
Suppose there exists another representation using coins from {c⁰, c¹, ..., c^k}: n = b_k · c^k + b_{k-1} · c^{k-1} + ... + b₁ · c + b₀
where b_i are non-negative integers (not necessarily < c).
Claim: For any representation with Σb_i > Σa_i (more coins), there exists a transformation that reduces the total coins.
Argument: If any coefficient b_i ≥ c, we can write:
- b_i · c^i = c · c^i + (b_i - c) · c^i = 1 · c^{i+1} + (b_i - c) · c^i
This replaces c coins of denomination c^i with 1 coin of denomination c^{i+1}, reducing the total count by c - 1 > 0.
By repeatedly applying this reduction, we transform any representation into one where each coefficient is < c.
Uniqueness: When restricted to coefficients 0 ≤ b_i < c, the representation is unique (standard base-c property).
Conclusion: The base-c representation (computed by greedy) is the unique representation with the minimum number of coins.
Therefore, the greedy algorithm always yields an optimal solution for denominations that are powers of c. ∎
Part (b): Counterexample
Claim: There exist coin denominations for which the greedy algorithm does not yield an optimal solution.
Counterexample:
Denominations: {1, 3, 4} Target amount: n = 6 cents
Greedy solution:
- Use 4 cents: leaves 2 cents remaining
- Use 1 cent twice: leaves 0 cents
- Total: 3 coins (one 4-cent coin and two 1-cent coins)
Optimal solution:
- Use 3 cents twice: leaves 0 cents
- Total: 2 coins (two 3-cent coins)
Since 2 < 3, the greedy algorithm (using 3 coins) does not produce an optimal solution (which uses 2 coins). ✓
This counterexample satisfies the requirement that 1-cent coins are included (ensuring a solution exists for all values of n).
COMP 382 Homework 5 — Grading Report
Problem 1: Greedy Trucking
Score: 17/20 points
Assessment:
Approach: The student uses an exchange/induction argument to show greedy is optimal, arguing that the greedy partition maximizes boxes per truck and any deviation requires at least as many trucks.
Strengths:
- Correctly formalizes the greedy invariant: boxes in the first truck plus the next box exceed capacity W
- Clearly identifies that order constraints force any valid solution to respect truck boundaries
- Solid overall proof structure with induction on remaining boxes
Errors/Gaps:
- The statement "any solution must 'complete' the delivery of boxes 1..m₁ before starting on subsequent boxes" is somewhat tautological given the ordering constraint—the key insight that needs more emphasis is that any other solution must use at least one truck for the first ≤ m₁ boxes, and if it uses fewer boxes in its first truck, it can only do worse
- The inductive step is asserted ("By induction on the remaining boxes") rather than carefully argued—specifically, the student doesn't formally show that if the alternative solution uses fewer boxes in its first truck, the remaining subproblem is at least as hard
- Labeled as "exchange argument" but the proof is really a "stays ahead" induction; the classical exchange structure (transforming OPT into greedy step-by-step) is not fully carried out
Detailed Feedback: The proof captures the essential logic: greedy packs as many boxes as possible into each truck, and any solution that packs fewer boxes into a truck cannot do better overall. The argument is largely correct but would benefit from a more explicit inductive step. The reference solution's "stays ahead" formulation (greedy fits at least as many boxes in the first k trucks as any other solution) is cleaner, but the student's approach is fundamentally sound. Minor deductions for the gaps in the inductive argument.
Rubric Breakdown:
- Correct greedy characterization: 5/5
- Proof structure (induction/exchange): 4/5
- Inductive step rigor: 4/5
- Completeness and clarity: 4/5
---
Problem 2: Smallest Set of Intervals Containing Points
Score: 18/20 points
Assessment:
Approach: The student presents the correct greedy algorithm (sort points, create intervals starting at the leftmost uncovered point) and proves optimality using a shifting argument combined with induction.
Strengths:
- Algorithm matches the reference solution exactly
- Nice addition of the "shifting argument" showing WLOG an optimal solution can have interval left endpoints at point positions
- Clear inductive argument: greedy's first interval covers the maximum range, then recurse
- Well-structured proof with the exchange/optimality principle
Errors/Gaps:
- The pseudocode has a bug: the condition
x_i ≤ x_i + 1is always true (any number is less than itself + 1). This should read something likex_i ≤ x_first + 1wherex_firstis the left endpoint of the current interval. The conceptual description is correct, but the pseudocode as written doesn't properly skip covered points.
Detailed Feedback: The student demonstrates a thorough understanding of this problem. The algorithm is correct, and the proof is well-organized with the shifting argument being a valuable addition over the reference. The pseudocode bug is clearly a notational error rather than a conceptual one, as the surrounding text makes the intent clear. Small deduction for the pseudocode issue.
Rubric Breakdown:
- Correct algorithm description: 4/5
- Algorithm pseudocode: 4/5 (bug in skip condition)
- Proof of optimality: 5/5
- Completeness: 5/5
---
Problem 3: All Spanning Trees
Score: 14/20 points
Assessment:
Approach: The student constructs a valid edge ordering by placing T-edges before non-T-edges within each weight class. This is a correct and well-known approach, different from the reference solution's weight-perturbation method.
Strengths:
- The construction (T-edges first within each weight class) is correct and creative
- Correctly identifies the three-part verification needed
- Invokes the cycle property of MSTs
Errors/Gaps:
- Internal contradiction in the proof: The student writes "At least one edge in C \ {e} is not in the current forest" immediately followed by "there is already a path connecting e's endpoints using edges from T." These two statements contradict each other—the second is correct, the first is wrong.
- Missing key justification: The proof does not explicitly argue *why* all edges of the fundamental cycle of e (in T) have weight ≤ w(e). This is the critical MST property needed: for any non-tree edge e, all tree edges on the path between e's endpoints have weight ≤ w(e). Without this, we can't conclude that all cycle edges are already in the forest when e is processed.
- The argument for T-edges being added ("since T is acyclic") is slightly thin—needs to also argue they don't create cycles with previously added non-T-edges from lower weight classes. (Though this follows because Kruskal only adds non-cycle edges.)
Detailed Feedback: The student's construction is the most creative and difficult part of this problem, and it is correct. The reference solution takes a different approach (perturbing weights), but the student's approach is equally valid. However, the verification has significant issues. The internal contradiction is concerning, and the key MST property that makes the construction work (all edges in a fundamental cycle of a non-tree edge have weight ≤ the non-tree edge's weight) is not stated or proved. The conclusion is correct, but the path to get there has gaps and errors.
Rubric Breakdown:
- Correct construction of edge ordering: 8/8
- Proof that T-edges are added: 3/4 (slightly thin justification)
- Proof that non-T-edges are rejected: 2/5 (contradiction, missing key property)
- Overall coherence: 1/3
---
Problem 4: Longest Oscillating Subsequence
Score: 10/20 points
Assessment:
Approach: The student presents a greedy scan that tracks direction and greedily takes the first element that reverses the current direction.
Strengths:
- Clear problem understanding and well-defined algorithm with pseudocode
- Correct identification of the need to track direction (UP/DOWN)
- Structured proof attempt with exchange argument
Errors/Gaps:
- Fundamental algorithm bug: The algorithm does NOT update
last_elementwhen the current trend continues. This means it can get stuck with a suboptimal value and miss valid subsequences.
Counterexample demonstrating the bug:
Consider A = [1, 2, 10, 9, 3, 11]:
- Takes 1 (length=1), then 2 (UP, length=2, last_element=2)
- Sees 10: direction is UP, needs DOWN, 10 < 2? No → skip
- Sees 9: 9 < 2? No → skip
- Sees 3: 3 < 2? No → skip
- Sees 11: 11 < 2? No → skip
- Output: 2
But the correct answer is 4: subsequence [1, 10, 3, 11] gives 1 < 10 > 3 < 11 ✓
The fix would be to update last_element when seeing a value that continues the current trend (e.g., when UP and seeing a higher value, update last_element to track the peak). The reference solution avoids this by finding "runs" (maximal monotone subarrays) and taking their extrema.
- Proof is invalid: Since the algorithm is incorrect, the exchange argument proof is necessarily flawed. The claim that "greedy picks the earliest element that continues the alternating pattern, maximizing future options" is precisely backwards—taking the earliest UP element (2) rather than the peak (10) *minimizes* future options.
Detailed Feedback:
The student demonstrates understanding of the problem structure and the general greedy approach. The algorithm is close to correct—it just needs the addition of updating last_element during continued trends to track peaks and valleys. This is equivalent to the reference solution's "runs" approach. However, as written, the algorithm produces provably wrong answers on simple inputs. The proof, while well-structured, attempts to justify an incorrect algorithm. Partial credit is awarded for correct problem understanding and a reasonable (if flawed) approach.
Rubric Breakdown:
- Problem understanding: 4/4
- Algorithm correctness: 2/8 (close structure but fundamental bug)
- Proof of correctness: 2/6 (structured but proves wrong algorithm)
- Pseudocode clarity: 2/2
---
Problem 5: Coin Changing
Score: 20/20 points
Assessment:
Approach: Part (a) uses the base-c representation argument; Part (b) uses the {1, 3, 4} counterexample with n=6.
Strengths:
- Clean, correct greedy algorithm for power-of-c denominations
- Elegant proof connecting to base-c number system
- Key insight clearly stated: if any coefficient b_i ≥ c, we can reduce the coin count by replacing c coins of c^i with 1 coin of c^{i+1}
- Uniqueness argument via base-c representation is rigorous
- Counterexample matches the reference solution and is clearly verified
Errors/Gaps:
- None significant
Detailed Feedback: This is an excellent solution to both parts. Part (a) correctly establishes that the greedy solution corresponds to the base-c representation, and the proof that no coefficient needs to be ≥ c (since c coins of one denomination equal 1 coin of the next) is clean and convincing. The uniqueness argument properly closes the proof. Part (b) provides the standard counterexample with clear verification.
Rubric Breakdown:
- Part (a) algorithm: 4/4
- Part (a) proof of optimality: 9/9
- Part (b) counterexample: 4/4
- Part (b) verification: 3/3
---
Overall Summary
| Problem | Score | Notes |
|---|---|---|
| 1: Greedy Trucking | 17/20 | Correct approach, inductive step could be tighter |
| 2: Intervals | 18/20 | Correct algorithm and proof, minor pseudocode bug |
| 3: All Spanning Trees | 14/20 | Correct construction, but proof has contradiction and gaps |
| 4: Oscillating Subsequence | 10/20 | Algorithm has fundamental correctness bug (doesn't track peaks/valleys) |
| 5: Coin Changing | 20/20 | Both parts correct and well-explained |
| Total | 79/100 |
General Comments:
The student demonstrates solid understanding of greedy algorithms and proof techniques across most problems. Problems 1, 2, and 5 are well-done with only minor issues. Problem 3 shows a correct and creative construction but the verification proof needs more care. The main area for improvement is Problem 4, where a subtle but critical algorithm bug (not updating the tracked element during continued trends) leads to incorrect results. The student should test algorithms on more diverse inputs, particularly cases with long monotone runs, to catch such bugs. Overall, good work with a strong showing on the coin changing problem.
Total: 79/100
diff --git a/writeup.md b/writeup.md
index 76d2b84..b9f6ba5 100644
--- a/writeup.md
+++ b/writeup.md
@@ -1,9 +1,285 @@
# COMP382 Homework 5
-## Student Responses
+## Problem 1: Greedy Trucking [20 points]
-<!-- Write your solutions below. Add sections for each problem as needed. -->
-<!-- Use proper mathematical notation where applicable. -->
+**Claim:** The greedy algorithm that packs boxes in order of arrival and sends trucks when the next box doesn't fit minimizes the number of trucks needed.
-[Your solutions here]
+**Proof:**
+
+Let G be the solution produced by the greedy algorithm using k trucks, and let O be any other valid solution using k* trucks (satisfying the constraint that boxes are shipped in arrival order).
+
+We prove by exchange argument that k ≤ k*, i.e., greedy is optimal.
+
+**Key observation:** When greedy sends truck i, it contains boxes from position s_i to position e_i (in arrival order) such that:
+- The total weight of these boxes fits in capacity W
+- The total weight of these boxes PLUS the next box (at position e_i + 1) exceeds W
+
+Formally: Σ(w_j : s_i ≤ j ≤ e_i) ≤ W and Σ(w_j : s_i ≤ j ≤ e_i + 1) > W
+
+**Exchange argument:**
+
+Since boxes must be shipped in arrival order in any valid solution, consider the partition created by greedy: {boxes 1..m₁}, {boxes (m₁+1)..m₂}, ..., {boxes (m_{k-1}+1)..n}.
+
+For the first partition {boxes 1..m₁}:
+- These boxes cannot fit together with box (m₁ + 1) in a single truck: w₁ + ... + w_{m₁} + w_{m₁+1} > W
+- Therefore, in any solution, truck(s) carrying boxes 1..m₁ cannot also carry box m₁ + 1
+- This means any solution must "complete" the delivery of boxes 1..m₁ before starting on subsequent boxes
+
+By induction on the remaining boxes, the greedy choice (completing the first partition as much as possible before starting a new truck) is optimal. Any solution that deviates from this partition uses at least as many trucks.
+
+Therefore, the greedy algorithm minimizes the number of trucks. ∎
+
+---
+
+## Problem 2: Smallest Set of Intervals Containing Points [20 points]
+
+**Algorithm:**
+
+Input: Set of points {x₁, x₂, ..., x_n} on the real line
+Output: Minimum set of unit-length closed intervals covering all points
+
+1. Sort the points: x₁ ≤ x₂ ≤ ... ≤ x_n
+2. Let I = [] (list of intervals)
+3. i ← 1
+4. While i ≤ n:
+ - Create interval I_current ← [x_i, x_i + 1]
+ - Add I_current to I
+ - While i ≤ n and x_i ≤ x_i + 1 (all points still covered): i ← i + 1
+ - (This skips all points covered by I_current)
+5. Return I
+
+**Proof of Correctness:**
+
+We prove that this greedy algorithm produces an optimal solution using an exchange argument.
+
+**Claim:** For any set of points, there exists an optimal solution where one of the intervals has its left endpoint at some point's position.
+
+**Proof:** Consider any optimal solution O with intervals [a₁, a₁+1], [a₂, a₂+1], ..., [a_k, a_k+1]. If some interval [a_i, a_i+1] doesn't have a point at its left endpoint, we can shift it left until a point touches the left endpoint, without losing coverage. This transformation cannot increase the number of intervals, so we can assume OPT has this property.
+
+**Main argument:**
+
+Let G = {I₁, I₂, ..., I_k} be the greedy solution and O = {J₁, J₂, ..., J_{k*}} be an optimal solution.
+
+Our greedy algorithm chooses I₁ = [x₁, x₁+1], which:
+- Covers all points up to x₁ + 1
+- Is the optimal choice for covering x₁ (the leftmost uncovered point)
+ - Any interval covering x₁ must have left endpoint ≤ x₁
+ - To maximize coverage to the right, we choose left endpoint = x₁, giving [x₁, x₁+1]
+ - This covers the maximum possible range starting from x₁
+
+By the principle of optimality, any optimal solution covering x₁ covers at most the same set of points with one interval as our greedy choice.
+
+If O covers the same points up to x₁+1 with one interval, then removing these points from both solutions and applying induction:
+- The remaining problem (covering remaining points) requires at least k* - 1 intervals in any solution
+- Greedy solves the remaining problem optimally (by induction)
+- Therefore k = 1 + (k-1) ≤ 1 + (k* - 1) = k*
+
+If O uses fewer intervals than greedy for the same set of points, it contradicts the optimality of O.
+
+Therefore, the greedy algorithm produces an optimal solution. ∎
+
+---
+
+## Problem 3: All Spanning Trees with Kruskal's Algorithm [20 points]
+
+**Claim:** For each minimum spanning tree T of graph G, there exists a sorting of the edges such that Kruskal's algorithm returns T.
+
+**Proof:**
+
+Recall that Kruskal's algorithm:
+1. Sorts edges by weight in non-decreasing order
+2. For each edge in this order, adds it to the current forest if it doesn't create a cycle
+3. Stops when n-1 edges are added
+
+When multiple edges have equal weight, Kruskal's result depends on the order in which edges of equal weight are considered.
+
+**Construction of sorting:**
+
+Given any MST T of G, we construct a sorting as follows:
+
+Partition edges by weight: E_w₁, E_w₂, ..., E_w_m where edges in E_w_i all have weight w_i and w₁ < w₂ < ... < w_m.
+
+Sort the edges with the following rule:
+- All edges in E_w₁ come before all edges in E_w₂, etc. (by original weights)
+- Within each weight class E_w_i:
+ - Edges in T ∩ E_w_i come before edges in E_w_i \ T
+ - The order within T ∩ E_w_i is arbitrary
+ - The order within E_w_i \ T is arbitrary
+
+**Verification that Kruskal returns T:**
+
+When Kruskal processes edges in this order:
+
+1. **For edges in T ∩ E_w_i:**
+ - These are processed first within weight class w_i
+ - Each edge in T ∩ E_w_i doesn't create a cycle in T (since T is acyclic)
+ - Therefore, Kruskal adds each edge in T ∩ E_w_i to its forest
+
+2. **For edges in E_w_i \ T:**
+ - These are processed after all edges in T ∩ E_w_i
+ - Consider any edge e ∈ E_w_i \ T
+ - By the cycle property of MSTs: since e ∉ T, adding e to T creates a unique cycle C
+ - At least one edge in C \ {e} is not in the current forest (by construction of the proof)
+ - When Kruskal processes e, there is already a path connecting e's endpoints using edges from T
+ - Therefore, e creates a cycle and is correctly rejected by Kruskal
+
+3. **Result:**
+ - Kruskal adds exactly the edges in T
+ - Since T is an MST with the same total weight as any other MST, Kruskal's output is an MST
+ - Kruskal's output is exactly T
+
+Therefore, for any MST T, there exists an edge sorting that makes Kruskal return T. ∎
+
+---
+
+## Problem 4: Longest Oscillating Subsequence [20 points]
+
+**Definition:** A sequence is oscillating if elements alternate between increasing and decreasing:
+- Either: x₁ < x₂ > x₃ < x₄ > ... (down-up pattern)
+- Or: x₁ > x₂ < x₃ > x₄ < ... (up-down pattern)
+
+**Greedy Algorithm:**
+
+Input: Array A[1..n] of integers
+Output: Length of longest oscillating subsequence
+
+```
+if n ≤ 1: return n
+
+last_element ← A[1]
+length ← 1
+last_direction ← NONE (indicates no comparison yet)
+
+for i ← 2 to n:
+ if last_direction = NONE:
+ if A[i] ≠ last_element:
+ last_element ← A[i]
+ if A[i] > A[i-1]:
+ last_direction ← UP
+ else:
+ last_direction ← DOWN
+ length ← length + 1
+ else if last_direction = UP:
+ // We need to go DOWN next
+ if A[i] < last_element:
+ last_element ← A[i]
+ last_direction ← DOWN
+ length ← length + 1
+ else: // last_direction = DOWN
+ // We need to go UP next
+ if A[i] > last_element:
+ last_element ← A[i]
+ last_direction ← UP
+ length ← length + 1
+
+return length
+```
+
+**Proof of Correctness:**
+
+**Claim:** The greedy algorithm returns the maximum length of any oscillating subsequence.
+
+**Proof:**
+
+Let G be the length returned by greedy, and let O be the length of any optimal oscillating subsequence.
+
+We prove G ≥ O using the greedy choice property.
+
+**Key insight:** At each step, when the greedy algorithm selects an element to extend the oscillation, it picks the earliest element that continues the alternating pattern. This choice maximizes the number of future elements available for selection.
+
+**Exchange argument:**
+
+Suppose O selects a different set of indices j₁, j₂, ..., j_{|O|}, and let greedy select i₁, i₂, ..., i_{|G|}.
+
+Let k be the first position where greedy and O differ (if they differ at all). Specifically:
+- Up to position k-1, both greedy and O have selected the same elements
+- At position k, greedy selects element at index i_k, and O selects element at index j_k where j_k > i_k
+
+**Case 1:** j_k ≤ n and elements at both indices satisfy the oscillation pattern from position k-1:
+- Since i_k < j_k and both extend the oscillation, greedy's earlier choice leaves more elements available for future positions
+- We can replace j_k with i_k in O without breaking the oscillation pattern
+- This transformation leaves the count unchanged but brings O closer to greedy's choices
+
+**Case 2:** Continuing this exchange argument position by position:
+- Each time O makes a different choice than greedy, we can swap to greedy's (earlier) choice
+- These swaps maintain the oscillation property and don't reduce the length
+- Eventually, we transform O into an equivalent or shorter sequence than greedy
+
+By this exchange argument, any oscillating subsequence has length ≤ greedy's length.
+
+Therefore, the greedy algorithm finds the longest oscillating subsequence. ∎
+
+---
+
+## Problem 5: Coin Changing [20 points]
+
+### Part (a): Power-of-c Denominations
+
+**Given:** Coin denominations are c⁰, c¹, c², ..., c^k for integers c > 1 and k ≥ 1
+
+**Greedy Algorithm:**
+
+Input: Target amount n, denominations c⁰, c¹, ..., c^k
+Output: Minimum number of coins to make amount n
+
+```
+coins ← 0
+for i ← k down to 0:
+ coins ← coins + ⌊n / c^i⌋
+ n ← n mod c^i
+return coins
+```
+
+**Proof of Optimality:**
+
+We prove the greedy algorithm always yields an optimal solution.
+
+**Key insight:** The denominations c⁰, c¹, ..., c^k form a base-c number system. The greedy algorithm computes the base-c representation of n.
+
+**Theorem:** For any positive integer n, there exist unique non-negative integers a₀, a₁, ..., a_k with 0 ≤ a_i < c such that:
+n = a_k · c^k + a_{k-1} · c^{k-1} + ... + a₁ · c + a₀
+
+**Proof:**
+
+Suppose there exists another representation using coins from {c⁰, c¹, ..., c^k}:
+n = b_k · c^k + b_{k-1} · c^{k-1} + ... + b₁ · c + b₀
+
+where b_i are non-negative integers (not necessarily < c).
+
+**Claim:** For any representation with Σb_i > Σa_i (more coins), there exists a transformation that reduces the total coins.
+
+**Argument:** If any coefficient b_i ≥ c, we can write:
+- b_i · c^i = c · c^i + (b_i - c) · c^i = 1 · c^{i+1} + (b_i - c) · c^i
+
+This replaces c coins of denomination c^i with 1 coin of denomination c^{i+1}, reducing the total count by c - 1 > 0.
+
+By repeatedly applying this reduction, we transform any representation into one where each coefficient is < c.
+
+**Uniqueness:** When restricted to coefficients 0 ≤ b_i < c, the representation is unique (standard base-c property).
+
+**Conclusion:** The base-c representation (computed by greedy) is the unique representation with the minimum number of coins.
+
+Therefore, the greedy algorithm always yields an optimal solution for denominations that are powers of c. ∎
+
+### Part (b): Counterexample
+
+**Claim:** There exist coin denominations for which the greedy algorithm does not yield an optimal solution.
+
+**Counterexample:**
+
+Denominations: {1, 3, 4}
+Target amount: n = 6 cents
+
+**Greedy solution:**
+- Use 4 cents: leaves 2 cents remaining
+- Use 1 cent twice: leaves 0 cents
+- Total: **3 coins** (one 4-cent coin and two 1-cent coins)
+
+**Optimal solution:**
+- Use 3 cents twice: leaves 0 cents
+- Total: **2 coins** (two 3-cent coins)
+
+Since 2 < 3, the greedy algorithm (using 3 coins) does not produce an optimal solution (which uses 2 coins). ✓
+
+This counterexample satisfies the requirement that 1-cent coins are included (ensuring a solution exists for all values of n).
Sub-Model Usage
| Model | Input | Output | Cache Read | Cost |
|---|---|---|---|---|
| claude-haiku-4-5-20251001 | 37 | 11.9K | 139.1K | $0.11 |
BSCS Bench