Problem · Dynamic Programming

Maximize Wall Hits

Learn this problem
HardOpenAI logoOpenAINEW GRADOA

Problem statement

You move along an infinite number line and start at coordinate 0. Each wall is located at a half-integer coordinate of the form x + 0.5, so it lies between two adjacent integer positions.

On each move, you step one unit to the left or right:

  • If the move does not cross a wall, it costs 1 unit of energy.
  • If the move crosses a wall with thickness t, it costs t units of energy and counts as one wall hit.

Walls remain in place after they are hit. You may change direction at any time and may cross the same wall repeatedly; every crossing counts as another hit.

Given the wall positions, their corresponding thicknesses, and the maximum amount of energy you may spend, return the maximum number of wall hits you can make without exceeding the energy limit.

Function

maximizeTheHits(walls: float[], thickness: int[], energy: int) → int

Complete the function maximizeTheHits.

  • float[] walls: wall positions, where walls[i] has thickness thickness[i]
  • int[] thickness: the energy cost of crossing each wall
  • int energy: the maximum total energy available

Return the maximum number of wall hits.

Examples

Example 1

walls = [-1.5, 0.5, 1.5, 5.5]thickness = [2, 4, 8, 3]energy = 3return = 1

Start at x = 0. Move left to x = -1 without crossing a wall, which costs 1 energy. Then move from x = -1 to x = -2, crossing the wall at -1.5. That crossing costs the wall's thickness, 2, and records one hit.

The total cost is 1 + 2 = 3, so no energy remains. Therefore, the maximum number of hits is 1.

More OpenAI problems

drafts saved locally
public int maximizeTheHits(float[] walls, int[] thickness, int energy) {
  // write your code here
}
walls[-1.5, 0.5, 1.5, 5.5]
thickness[2, 4, 8, 3]
energy3
expected1
checking account