Frog Jump II — LeetCode 2498 Python Solution

MediumGreedyArrayBinary Search
Problem
#2498
Reading time
2 min

The problem

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.

Example

Input
stones = [0,2,5,6,7]
Output
5
Explanation
The above figure represents one of the optimal paths the frog can take.

Python solution

Python
class Solution:
    def maxJump(self, stones: List[int]) -> int:
        ans = stones[1] - stones[0]
        for i in range(2, len(stones)):
            ans = max(ans, stones[i] - stones[i - 2])
        return ans

Complexity

MeasureComplexity
TimeO(log n) or O(n log n)
SpaceO(1) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 2498. Frog Jump II is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2498. Frog Jump II?
LeetCode 2498. Frog Jump II is rated Medium on LeetCode.
What topics does LeetCode 2498. Frog Jump II cover?
LeetCode 2498. Frog Jump II is tagged Greedy, Array and Binary Search on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview