2591. Frog Jump Ii¶
Difficulty: Medium
LeetCode Problem View on GitHub
2591. Frog Jump II
Medium
You are given a 0-indexed integer array stones sorted in strictly increasing order representing the positions of stones in a river.
A frog, initially on the first stone, wants to travel to the last stone and then return to the first stone. However, it can jump to any stone at most once.
The length of a jump is the absolute difference between the position of the stone the frog is currently on and the position of the stone to which the frog jumps.
- More formally, if the frog is at
stones[i]and is jumping tostones[j], the length of the jump is|stones[i] - stones[j]|.
The cost of a path is the maximum length of a jump among all jumps in the path.
Return the minimum cost of a path for the frog.
Example 1:

Input: stones = [0,2,5,6,7] Output: 5 Explanation: The above figure represents one of the optimal paths the frog can take. The cost of this path is 5, which is the maximum length of a jump. Since it is not possible to achieve a cost of less than 5, we return it.
Example 2:

Input: stones = [0,3,9] Output: 9 Explanation: The frog can jump directly to the last stone and come back to the first stone. In this case, the length of each jump will be 9. The cost for the path will be max(9, 9) = 9. It can be shown that this is the minimum achievable cost.
Constraints:
2 <= stones.length <= 1050 <= stones[i] <= 109stones[0] == 0stonesis sorted in a strictly increasing order.
Solution¶
class Solution {
public int maxJump(int[] stones) {
int n = stones.length;
int low = 0, high = (int)(1e9 + 10), ans = -1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (ok(mid, stones)) {
ans = mid;
high = mid - 1;
} else
low = mid + 1;
}
return ans;
}
private boolean ok(int target, int arr[]) {
int n = arr.length;
int currIdx = 0;
int vis[] = new int[n + 1];
while (currIdx < n) {
if (currIdx == n - 1)
break;
int low = currIdx + 1, high = n - 1, ans = -1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (Math.abs(arr[mid] - arr[currIdx]) <= target) {
ans = mid;
low = mid + 1;
} else
high = mid - 1;
}
if (ans == -1)
return false;
currIdx = ans;
vis[ans] = 1;
}
currIdx = n - 1;
while (currIdx >= 0) {
if (currIdx == 0)
return true;
int low = 0, high = currIdx - 1, ans = -1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (Math.abs(arr[mid] - arr[currIdx]) > target)
low = mid + 1;
else if (Math.abs(arr[mid] - arr[currIdx]) <= target && vis[mid] == 0) {
ans = mid;
high = mid - 1;
} else
low = mid + 1;
}
if (ans == -1)
return false;
currIdx = ans;
vis[ans] = 1;
}
return true;
}
}
Complexity Analysis¶
- Time Complexity:
O(?) - Space Complexity:
O(?)
Approach¶
Detailed explanation of the approach will be added here