← Questions

Max flight distance with limited energy

0
GoogleCoding

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 = 0 mean you can never fly?
  • Is resting at full energy allowed, just wasted?
  • Can k be larger than n? Then, in practice, the cap never matters past n.
  • 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 with n <= 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, and n = 0.

Follow-ups

  • Return the plan, using a stored choice table or a second pass.
  • n up to 10^5: is there a greedy with a heap, and why does it work?
  • Resting gains r energy, or flying costs a different amount each day.
  • Some days must be rest days.

Where it's asked

What it tests

dynamic programming · arrays · greedy

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