Problem · Array

Rock Jumping

Learn this problem
MediumIMIMCNEW GRADOA

Problem statement

You are standing on the left bank of a river that is width units wide, and you are aiming to reach the right bank. The left bank is located at x = 0 and the right bank is located at x = width. There are several rocks in the river at various x-coordinates between the banks, each with a specific height. You can jump between rocks or directly to the right bank.

The cost to jump between two locations is the square of the distance between them: (x[i] - x[j])^2.

The water level is rising over time. Once the water reaches a certain level, some rocks will be submerged and can no longer be used for jumping. A rock is considered submerged if the water level is higher than its height. The water stops rising once you start your first jump.

There is a maximum jump distance maxJump and a maximum total energy maxEnergy that you can use to cross the river. The total energy cost of all jumps must not exceed maxEnergy.

Determine the maximum water height at which you can still reach the other side of the river without exceeding maxJump or maxEnergy.

You are provided with four integers: width, the width of the river; numRocks, the number of rocks; maxJump, the maximum jump distance; and maxEnergy, the maximum total energy.

You are also provided with two integer arrays: x, containing the x-coordinate of each rock, and heights, containing the height of each rock. Rocks are located strictly between the banks, so 0 < x[i] < width.

Return a single integer representing the maximum water height at which you can still reach the other side of the river. If it is impossible to reach the other side, return -1. If it will always be possible to reach the other side, return 10^9.

Function

maxWaterHeight(width: int, numRocks: int, maxJump: int, maxEnergy: long, x: int[], heights: int[]) → int

Examples

Example 1

width = 10numRocks = 2maxJump = 10maxEnergy = 40x = [4, 7]heights = [3, 5]return = 3

Constraints

  • 1 <= width, maxJump <= 10^9
  • 1 <= maxEnergy <= 10^18
  • 1 <= numRocks <= 10^5
  • 0 < x[i] < width
  • 0 <= heights[i] <= 10^9
  • x is in ascending order.

More IMC problems

drafts saved locally
public int maxWaterHeight(int width, int numRocks, int maxJump, long maxEnergy, int[] x, int[] heights) {
  // write your code here
}
width10
numRocks2
maxJump10
maxEnergy40
x[4, 7]
heights[3, 5]
expected3
checking account