minimum number of jumps in java
Given an array of N integers arr[] where each element represents the maximum length of the jump that can be made forward from that element. This means if arr[i] = x, then we can jump any distance y such that y ≤ x.
Find the minimum number of jumps to reach the end of the array (starting from the first element). If an element is 0, then you cannot move through that element.
Note: Return -1 if you can't reach the end of the array.
Example 1:
Input:
N = 11
arr[] = {1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9}
Output: 3
Solution :
The solution we are going to see is based on the greedy approach. We keep track of the current and farthest reachable indices and make a jump whenever we reach the farthest reachable index from the current position. We also handle cases where we can't move forward (i.e. the current element is 0) or we've reached the end of the array. The time complexity of this algorithm is O(n), where n is the length of the input array.
Related Articles :
1. Trapping Rain Water Solution in Java
2. How to rotate an array in Java
4. Next Permutation Solution in Java
5. Divide two integers solution in java
6. Merge two sorted linked list in Java
8. Palindrome number solution in java
9. Median of two sorted arrays in Java