According to Wikipedia:
A greedy algorithm is an algorithmic paradigm that follows the solution of the heuristic problem, which allows making a locally optimal choice at each stage with the hope of finding a global optimum.
Here I want to draw your attention to the key phrase locally optimal choice at each stage , which makes the algorithmic paradigm greedy.
Q1. What is the intuition behind using a greedy algorithm for this?
Since in this question we only care about whether the last index of the array can be reached, we can use the greedy algorithm. The greedy algorithm will choose the optimal choice (take the maximum jump) at each step and at the end check if the maximum index reaches.
Say, if we need to find out the size of the transition for each index in order to achieve the goal or if we need to optimize the number of jumps to reach the end, then the direct use of the greedy algorithm will not serve our purpose.
Q2. How is the above solution a greedy algorithm?
The if condition in the above code is if(i+A[i]>=last)last=i; makes the algorithm greedy because we take the maximum jump if possible ( i+A[i]>=last ).
The analysis provided here may help you.
Edit
Tell us about what you indicated - [3,3,1,0,4] .
- When
i=0 , the algorithm checks which maximum index we can reach from i=0 . - Then we move on to the next index and check what maximum index we can reach from
i=1 . Since we moved to i=1 , we guarantee that we can go to index 1 from index 0 (no matter what the size of the transition).
Please note that in this problem we donβt care whether we should jump in size 3 at i=0 , although we know that this will not help us achieve our goal. We care about whether we can reach the end or beyond this end by jumping.
source share