Path Sum with Conditional Prime Shortcuts
Dynamic ProgrammingAuto-graded · 16 test casesLast updated
Tests dynamic programming with number theory constraints, combining sequential traversal with prime-offset jumps that depend on target cell properties.
You are given an array nums containing n positive integers. Your task is to traverse from the first position (index 0) to the final position (index n-1), collecting values at each position you visit. You want to maximize the total sum of collected values.
From any position i, you have two types of moves available:
- Sequential step: Move forward one position to
i + 1 - Prime shortcut: Jump forward by
ppositions toi + p, wherepis a prime number, but only if the value at the destinationnums[i + p]has3as its last digit (i.e.,nums[i + p] % 10 == 3)
You must visit the starting position 0 and the ending position n-1, collecting their values. Return the maximum possible sum you can achieve.
Write a function that takes the array and returns this maximum sum.
Constraints
2 <= n <= 5000wheren = len(nums)1 <= nums[i] <= 100000- You must start at index
0and end at indexn-1 - All intermediate positions you visit contribute their values to the sum
- Sequential steps are always allowed; prime shortcuts require the destination value to end in digit
3
Examples
Example 1
Input: max_path_sum([1, 5, 13, 2, 3])
Output: 24
Example 2
Input: max_path_sum([10, 2, 8])
Output: 20
Hints
Hint 1
Consider this a graph problem where you move strictly forward through indices. What property makes it suitable for dynamic programming?
Hint 2
Precompute all prime numbers up to n using the Sieve of Eratosthenes, since no jump can exceed the array length.
Hint 3
Track the maximum sum achievable when reaching each index. For positions ending in 3, check if arriving via a prime-offset jump from an earlier position gives a better result than sequential steps.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem is a longest-path problem on a directed acyclic graph (DAG). Since all moves go strictly forward through increasing indices, we can solve it with dynamic programming in index order.
Define dp[i] as the maximum sum achievable when reaching position i, including all values collected along the path from position 0 to position i.
Base case: dp[0] = nums[0] since we start at index 0 and collect its value.
Transitions: For each position j from 1 to n-1:
- We can always arrive via a sequential step from
j-1, giving sumdp[j-1] + nums[j] - If
nums[j]ends in digit3, we can also arrive via a prime jump from any earlier positionj-pwherepis prime, giving sumdp[j-p] + nums[j] - Take the maximum across all valid arrival methods
The algorithm processes positions left to right. When computing dp[j], all positions before j have already been processed, so their dp values are final. This ensures correctness.
Prime generation: Use the Sieve of Eratosthenes to generate all primes less than n, since no jump can exceed the array bounds. This takes O(n log log n) time.
Why it works: The sequential step is always available, so every position is reachable. The prime shortcuts can only skip over positions, and since all values are positive, skipping positions reduces the total sum. Therefore, while prime jumps are conditionally available, the optimal path under these constraints is to visit every position sequentially, giving a sum equal to the total of all array elements.
Complexity
- Time: O(n · π(n)) where π(n) is the count of primes less than n. For each position ending in
3, we check all primes up to that index. Since π(n) ≈ n/ln(n), this is approximately O(n²/log n). The sieve adds O(n log log n). - Space: O(n) for the dp array and prime list.
Solution Code
from typing import List
def max_path_sum(nums: List[int]) -> int:
n = len(nums)
is_prime = [True] * n
if n > 0:
is_prime[0] = False
if n > 1:
is_prime[1] = False
p = 2
while p * p < n:
if is_prime[p]:
for multiple in range(p * p, n, p):
is_prime[multiple] = False
p += 1
primes = [p for p in range(2, n) if is_prime[p]]
dp = [0] * n
dp[0] = nums[0]
for j in range(1, n):
best = dp[j - 1]
if nums[j] % 10 == 3:
for jump in primes:
if jump > j:
break
candidate = dp[j - jump]
if candidate > best:
best = candidate
dp[j] = best + nums[j]
return dp[-1]