Greedy Algorithm Patterns
Tutorial Video
Text description (accessibility)
This video demonstrates the "Greedy Algorithm Patterns" functional Rust example. Difficulty level: Fundamental. Key concepts covered: Functional Programming. Greedy algorithms make locally optimal choices at each step, hoping for a global optimum. Key difference from OCaml: | Aspect | Rust | OCaml |
Tutorial
The Problem
Greedy algorithms make locally optimal choices at each step, hoping for a global optimum. Unlike dynamic programming which considers all subproblems, greedy algorithms commit to a choice and never reconsider. When a greedy choice property holds — meaning there always exists an optimal solution that includes the greedy choice — greedy algorithms are correct and typically O(n log n) (dominated by sorting). Classic greedy problems: interval scheduling (schedule maximum activities), fractional knapsack, Huffman coding, Prim's/Kruskal's MST, and coin change (for standard denominations). Recognizing when greedy works (and when it fails) is a key algorithm design skill.
🎯 Learning Outcomes
Code Example
#![allow(clippy::all)]
//! PlaceholderKey Differences
| Aspect | Rust | OCaml |
|---|---|---|
| Sort key | sort_by_key(|&(_, end)| end) | List.sort with comparison fn |
| Initialization | i32::MIN | Int.min_int |
| Accumulation | mut last_end + push | fold_left with acc tuple |
| Fractional knapsack | Sort by v/w with f64 | Same with float |
| Correctness proof | Exchange argument | Same mathematical argument |
| Failure cases | 0/1 knapsack example | Same |
OCaml Approach
OCaml's interval scheduling uses List.sort (fun (_, e1) (_, e2) -> compare e1 e2) then List.fold_left accumulating selected intervals. The greedy decision is if start >= last_end. OCaml's Int.min_int initializes last_end. The fractional knapsack sorts by ratio using List.sort and fills greedily with List.fold_left. OCaml's pattern destructuring let (start, end_) = interval reads naturally. The Printf module formats activity schedules for verification.
Full Source
#![allow(clippy::all)]
//! PlaceholderDeep Comparison
OCaml vs Rust: Greedy Algorithm Patterns
Overview
See the example.rs and example.ml files for detailed implementations.
Key Differences
| Aspect | OCaml | Rust |
|---|---|---|
| Type system | Hindley-Milner | Ownership + traits |
| Memory | GC | Zero-cost abstractions |
| Mutability | Explicit ref | mut keyword |
| Error handling | Option/Result | Result<T, E> |
See README.md for detailed comparison.