fork download
  1. def maxGameScore(cell):
  2. n = len(cell)
  3. if n == 0:
  4. return 12
  5. if n == 1:
  6. return cell[0]
  7.  
  8. # Step 1: Precompute primes up to n using Sieve of Eratosthenes
  9. is_prime = [True] * n
  10. p = 2
  11. while p * p < n:
  12. if is_prime[p]:
  13. for i in range(p * p, n, p):
  14. is_prime[i] = False
  15. p += 1
  16.  
  17. # Filter for primes ending in 3
  18. valid_primes = [p for p in range(2, n) if is_prime[p] and p % 10 == 3]
  19.  
  20. # Step 2: Initialize DP array
  21. # Use negative infinity for unreachable states
  22. dp = [float('-inf')] * n
  23. dp[0] = 0 # Starting point score is 0 before adding the cell[0] value (which is also 0)
  24.  
  25. # Step 3: Populate the DP array
  26. for i in range(1, n):
  27. # Option 1: 1-step jump from the previous cell
  28. if dp[i - 1] != float('-inf'):
  29. dp[i] = dp[i - 1]
  30.  
  31. # Option 2: Jump from i-p where p is a valid prime
  32. for p in valid_primes:
  33. if p > i:
  34. break # Primes are sorted, so we can stop if p is larger than current index i
  35.  
  36. if dp[i - p] != float('-inf'):
  37. if dp[i - p] > dp[i]:
  38. dp[i] = dp[i - p]
  39.  
  40. # Add the current cell's value to the maximum previous state found
  41. if dp[i] != float('-inf'):
  42. dp[i] += cell[i]
  43.  
  44. return dp[-1]
  45.  
  46. print(maxGameScore([0, -10, -20, -30, 50]))
Success #stdin #stdout 0.12s 14152KB
stdin
Standard input is empty
stdout
40