Cross the most walls on a number line with limited energy
I was asked this
No reports yet. Sign in to say where you were asked it.
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.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to submit your code; every attempt is kept here.
