← Questions

Cross the most walls on a number line with limited energy

0
Scale AICoding

Walls stand at distinct non-zero integer points on an infinite number line. Wall k is at positions[k] and costs costs[k] >= 0 energy to cross.

You start at 0 with energy units. Each step moves you one unit left or right and costs 1 energy. A wall at x > 0 is crossed every time you step between x - 1 and x, in either direction. A wall at x < 0 is crossed every time you step between x + 1 and x. Each crossing costs that wall's cost again, on top of the step. Your total spend can never go over energy, and you may stop anywhere.

Implement:

def max_walls(energy: int, positions: list[int], costs: list[int]) -> int:
    ...

Return the largest number of distinct walls you can cross.

Constraints

  • 0 <= len(positions) == len(costs) <= 10^5
  • -10^9 <= positions[k] <= 10^9, positions[k] != 0, all distinct
  • 0 <= costs[k] <= 10^9, 0 <= energy <= 10^15

Example 1

energy = 10, positions = [3, -2, 6], costs = [2, 1, 1] → 2

Walk right to 6: 6 steps plus costs 2 + 1 = 9. Crossing -2 and 3 instead needs 11.

Example 2

energy = 15, same walls → 3

Walk left to -2 and back to 0 (2 * (2 + 1) = 6), then right to 6 (9). Total: 15.

Reconstructed from the reported question; details may differ from what interviewers ask.

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding