KatInterview

Path Sum with Conditional Prime Shortcuts

Dynamic ProgrammingAuto-graded · 16 test cases
HardAuto-gradedDynamic Programmingdynamic-programmingnumber-theoryarrays

Last 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:

  1. Sequential step: Move forward one position to i + 1
  2. Prime shortcut: Jump forward by p positions to i + p, where p is a prime number, but only if the value at the destination nums[i + p] has 3 as 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 <= 5000 where n = len(nums)
  • 1 <= nums[i] <= 100000
  • You must start at index 0 and end at index n-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.