Max flight distance with limited energy
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked at Google. It tests dynamic programming, arrays and greedy.
You are planning a trip over n days. dist[i] is how far you can fly on day i (a non-negative integer). You start with k units of energy, and k is also the most energy you can hold.
Each day you do exactly one of two things:
-
Fly: spend 1 energy and cover
dist[i]. You cannot fly with 0 energy. -
Rest: gain 1 energy, but never more than
k.
Implement max_fly_distance(dist: list[int], k: int) -> int, which returns the largest total distance you can cover over the n days.
Constraints: 0 <= n <= 2000, 0 <= k <= 10^9, 0 <= dist[i] <= 10^6.
Example 1
dist = [4, 1, 7, 3], k = 1
output: 11
Fly on day 0 (4), rest on day 1, fly on day 2 (7), rest on day 3.
Example 2
dist = [1, 1, 10, 10, 10], k = 1
output: 21
Fly on day 0 (1), rest, fly (10), rest, fly (10). Resting on day 0 would gain nothing, because you are already at full energy.
A follow-up may ask you to return the day-by-day plan as well.
Clarifying questions
- Does
k = 0mean you can never fly? - Is resting at full energy allowed, just wasted?
- Can
kbe larger thann? Then, in practice, the cap never matters pastn. - Do we also need the day-by-day plan?
What a strong answer covers
- Defines a DP over (day, energy left) and takes the best of flying and resting each day.
- Caps the energy dimension at
min(k, n), since more energy than days left is never useful. That is O(n^2) time withn <= 2000, and O(n) memory with one rolling row. - Explains why greedy (fly on the largest days) can fail: the energy order and the cap limit which days you can pick.
- Tests both examples,
k = 0,k >= n(fly every day), all distances zero, andn = 0.
Follow-ups
- Return the plan, using a stored choice table or a second pass.
-
nup to10^5: is there a greedy with a heap, and why does it work? - Resting gains
renergy, or flying costs a different amount each day. - Some days must be rest days.
Where it's asked
What it tests
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
