āļø Bellman-Ford Algorithm
Currency exchange rates can create arbitrage opportunities - if you can exchange currencies in a cycle and end up with more money than you started! Bellman-Ford algorithm detects such opportunities by finding negative cycles in graphs with negative weights.
The Negative Weight Problem
Dijkstra's fails with negative weights. Bellman-Ford handles them:
Real-World Applications
- Currency Arbitrage: Detect profitable currency exchange cycles
- Routing Protocols: Handle negative costs (rebates, discounts)
- Negative Cycle Detection: Identify impossible/contradictory constraints
- Network Protocols: Distance-vector routing (RIP, BGP)
How Bellman-Ford Works
Relaxation Process
- Initialize distances (start = 0, others = ā)
- Relax all edges V-1 times
- After V-1 iterations, distances should be optimal
- One more relaxation: If any edge can still be relaxed, negative cycle exists!
Key insight: After V-1 iterations, if we can still relax, there's a negative cycle!
See Bellman-Ford in Action
Negative Cycle Detection
Why V-1 Iterations?
In a graph with V vertices, shortest path has at most V-1 edges. After V-1 relaxations, all shortest paths should be found.
If we can still relax after V-1 iterations, it means there's a cycle with negative total weight!
The Complete Code
Click Run to execute your code
Dijkstra vs Bellman-Ford
When to Use Each
| Aspect | Dijkstra | Bellman-Ford |
|---|---|---|
| Time Complexity | O((V+E) log V) | O(VE) |
| Negative Weights | No | Yes |
| Negative Cycles | Cannot detect | Can detect |
| Best For | Non-negative weights | Any weights, need cycle detection |
Currency Arbitrage Example
Convert exchange rates to graph: if you can exchange currencies in a cycle and end up with more money, there's a negative cycle (profitable arbitrage)!
Summary
What You've Learned
Bellman-Ford algorithm handles negative weights:
- Algorithm: Relax edges V-1 times, then check for cycles
- Time: O(VE) - Slower than Dijkstra
- Space: O(V)
- Advantage: Handles negative weights and detects negative cycles
- Applications: Currency arbitrage, routing protocols
- Key insight: If edges can still be relaxed after V-1 iterations, negative cycle exists
What's Next?
You've mastered Bellman-Ford! Next, we'll explore Minimum Spanning Tree (MST) - connecting all vertices with minimum total edge weight, perfect for network design and cluster analysis!
Enjoying these tutorials?