Google questions

Jump Game with Profit

GoogleMedium

You stand at index 0 of two parallel lists, jump and profit. At index i you either take it (collect profit[i] and move to i + 1 + jump[i]) or skip it (collect nothing and move to i + 1). The walk ends once your index is n or beyond, where n is the list length.

Part 1: Maximum collectable profit

You are given two lists of the same length, jump and profit, and you start at index 0.

At index i you choose one of two moves:

  • Take it: collect profit[i] and move to index i + 1 + jump[i].
  • Skip it: collect nothing and move to index i + 1.

You are done as soon as your index is n or more, where n is the list length. You may skip every index, and a profit can be negative, so taking an index is never forced.

Return the largest total profit you can collect over all ways of choosing take or skip at the indices you visit. The answer is always at least 0.

  1. Example 1
    jump
    [2,0,0,0]
    profit
    [5,4,3,2]
    Output
    9

    Why: Taking index 0 earns 5 and lands on index 3, where taking earns 2, for 7. Skipping index 0 and taking indices 1, 2 and 3 earns 4 + 3 + 2 = 9, which is the best.

Constraints

  • 1 <= len(jump) == len(profit) <= 10^5
  • 0 <= jump[i] <= 10^5
  • -10^4 <= profit[i] <= 10^4
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question