~/problems / 1-D dynamic programming / Intro DP

Best score with prime-3 jumps

medium ~25 min Uber

A board game track has squares 0..n-1, and square i carries nums[i] points (possibly negative). Your token starts on square 0 and must finish exactly on square n - 1. Every move goes forward by one of these distances:

  • exactly 1 square, or
  • exactly p squares, where p is a prime whose last decimal digit is 3: 3, 13, 23, 43, 53, 73, 83, 103, ... (note that 33, 63 and 93 are not prime).

A move may not overshoot square n - 1. Your score is the sum of nums over every square the token stands on, including square 0 and square n - 1. Squares jumped over score nothing.

Write max_jump_score(nums: list[int]) -> int that returns the highest possible score.

max_jump_score([2, -5, -5, 4, 1])       # 7    0 -> 3 -> 4: 2 + 4 + 1
max_jump_score([1, 2, 3])               # 6    single steps collect everything
max_jump_score([-1, -9, -9, -1])        # -2   one jump of 3
max_jump_score([5])                     # 5    already on the last square

Constraints: 1 <= len(nums) <= 20,000; -10**4 <= nums[i] <= 10**4.

Trying every earlier square as a jump origin is O(n²) and too slow at the top size. There are only a few hundred usable primes below 20,000.

Show hint

best[i] = nums[i] + max(best[i - 1], best[i - p] for each allowed prime p <= i). Build the list of allowed primes once with a sieve.

Topic: Intro DP. State, transition, base case; top-down memo vs bottom-up table.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc