[LeetCode] Frog Jump II

2498. Frog Jump II

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 to stones[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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
bool helper(vector<int>& A, int k) {
int n = A.size();
vector<int> use(n);
int l = 0, r = 0;
while(r + 1 < n) {
while(r + 1 < n and A[l] + k >= A[r + 1]) r += 1;
if(l == r) return false;
use[r] = true;
l = r;
}
l = r - 1;
while(l > 0) {
while(l > 0 and use[l]) l -= 1;
if(A[r] - A[l] > k) return false;
r = l;
l = r - 1;
}
return true;
}
public:
int maxJump(vector<int>& stones) {
int l = 0, r = stones.back(), res = stones.back();
while(l <= r) {
int m = l + (r - l) / 2;
bool pass = helper(stones, m);
if(pass) res = min(res, m);
if(pass) r = m - 1;
else l = m + 1;
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/12/11/PS/LeetCode/frog-jump-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.