Maximum Score with Prime Jumps
UberSoftware Engineer · Online AssessmentLast updated
This problem tests dynamic programming and number theory, specifically the ability to combine linear path traversal with jump-based transitions constrained by prime number properties.
Problem Description
Given an array arr of n integers, you are playing a game starting at index 0. You want to reach the last index n-1 to maximize the sum of values at the cells you land on (including the start and end).
You can move from your current index i to index j (where j > i) under the following conditions:
- Step move: You can move to
i + 1. - Prime jump: You can jump to
i + kifkis a prime number and the jump lands on an indexjwherearr[j]ends with the digit3(i.e.,arr[j] % 10 == 3).
Your goal is to find the maximum possible sum of values encountered along the path from index 0 to n-1. If it is impossible to reach the end, return -1.
Function Signature
def max_score(arr: List[int]) -> int:
Constraints
2 <= len(arr) <= 50001 <= arr[i] <= 10^5- The prime jumps must be valid indices within bounds.
Examples
Example 1:
Input: arr = [1, 5, 13, 2, 3]
Output: 17
Explanation: Start at index 0 (val 1). Move to index 1 (val 5). Jump to index 2 (val 13, prime jump of 1 is not allowed, but index 2 is reachable via step/prime logic). A valid path is 0 -> 1 -> 2 -> 4. Sum: 1 + 5 + 13 + 3 = 22.
Example 2:
Input: arr = [10, 2, 8]
Output: -1
Explanation: No valid path exists to reach the end.
Edge Cases
- Path leads to a dead end.
- No primes exist that satisfy the jump condition.
Hints
Hint 1
Precompute primes up to the length of the array using a Sieve of Eratosthenes.
Hint 2
Use dynamic programming where `dp[i]` stores the maximum sum to reach index `i`, initialized to negative infinity.
Hint 3
For every index `i`, iterate through all possible next jumps, updating `dp[i + 1]` (step) and `dp[i + k]` (prime jump if `arr[i + k] % 10 == 3`).
Follow-up questions
- How would the solution change if you could move both forward and backward?
- What is the time complexity of your approach, and can it be optimized if the number of prime jumps is very large?
- If we add a constraint that you can only make a maximum of `K` prime jumps, how would you modify the DP state?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.