Greedy algorithms make the locally best choice and never look back. They are only correct when you can prove the local choice never hurts. Here the key quantity is how far can I possibly reach?
A frog sits on the first pad of a row of lily pads. nums[i] is the longest hop the frog can make from pad i: it may land on any pad from 1 up to nums[i] places further along, and a pad marked 0 is a dead end. Write can_jump(nums) that returns True if the frog can reach the last pad, and False otherwise.
Examples
Input: nums = [1, 2, 0, 3, 0, 1]
Output: True
Explanation: hop 1 pad to index 1, then 2 pads to index 3, then 3 pads to the last pad
Input: nums = [2, 1, 0, 2, 3]
Output: False
Explanation: every route gets stuck on index 2, whose hop length is 0
Constraints
- Target: O(n) time, O(1) space (a DP over every possible jump is O(n^2) and unnecessary)
Goals
- Identify a greedy invariant (the furthest index reachable so far) that makes a DP unnecessary
- Argue why a greedy choice is safe before trusting it
- Solve in a single left-to-right pass