← Questions
Max profit when taking a value skips ahead
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Google's onsite coding round, last asked Oct 2025. It tests dynamic programming and arrays.
You walk an integer array from index 0. At each index i you choose: take it, gaining arr[i] and jumping to index i + 1 + arr[i], or skip it, gaining nothing and moving to i + 1. You stop once the index is past the end. Return the largest total you can collect.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
max_profit(arr: list[int]) -> int— values are non-negative in the main problem.
Example
max_profit([3, 1, 1, 1, 5]) -> 8 # take 3 (jump to 4), take 5
max_profit([2, 1, 5, 1, 3]) -> 5 # take 5, or take 2 then 3
max_profit([1, 2, 3, 4]) -> 5 # take 1 (jump to 2), skip 3, take 4
max_profit([0, 0, 4]) -> 4
Constraints
-
1 <= len(arr) <= 10^5,0 <= arr[i] <= 10^9; totals need 64 bits.
Clarifying questions
- Can values be zero? Taking a zero just moves one step, like a skip.
- Do I stop exactly at the end, or can a jump land anywhere past it?
- Do you want the best total only, or also the indices taken?
- Can values be negative? (That is the follow-up.)
What a strong answer covers
- The DP from the right:
best[i] = max(best[i + 1], arr[i] + best[i + 1 + arr[i]]), withbest[j] = 0forj >= n. O(n) time and space. - Why greedy (always take the biggest value in reach) fails, with a small counterexample.
- The equivalent top-down memoised recursion and its stack depth.
- Rebuilding the chosen indices from the table.
- Tests: all zeros, one element, a big value that jumps past everything.
Follow-ups
- Values can be negative, so a take can jump backwards. Now the moves form a graph that may have cycles. What rule guarantees termination (for example, each index may be taken at most once, or you must stop on a repeat), and how does the solution change from a DP to a search over states?
- Taking costs a fixed fee.
- You may take at most
kvalues.
Where it's asked
- Google · Onsite coding · Last asked Oct 202545 min · Usually two rounds, mostly in person: whiteboard plus a Chromebook with Google Docs · No AI (a pilot code-comprehension round lets candidates use Gemini)
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
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
