Input: nums =[4,9,6,10]Output: trueExplanation: In the first operation: Pick i =0 and p =3, and then subtract 3 from nums[0], so that nums becomes [1,9,6,10].In the second operation: i =1, p =7, subtract 7 from nums[1], so nums becomes equal to [1,2,6,10].After the second operation, nums is sorted in strictly increasing order, so the answer istrue.
Example 2:
1
2
3
Input: nums =[6,8,11,12]Output: trueExplanation: Initially nums is sorted in strictly increasing order, so we don't need to make any operations.
Example 3:
1
2
3
Input: nums =[5,8,3]Output: falseExplanation: It can be proven that there is no way to perform operations to make nums sorted in strictly increasing order, so the answer isfalse.
Prime Number Generation: Generate a list of prime numbers using the Sieve of Eratosthenes, since you may need to find prime numbers less than any element in the array.
Transformation Attempt: Iterate through the given array to try to transform it into a strictly increasing array.
Validation: For each element in the array, if it’s not possible to make the array strictly increasing, return false.
Conditions:
For each element nums[i], it must be strictly greater than the previous element nums[i-1] after any required operations.
Use the largest prime number less than nums[i] to achieve this if necessary.
classSolution:
defprimeSubOperation(self, nums: List[int]) -> bool:
defsieve_primes(max_num: int) -> List[int]:
is_prime = [True] * (max_num +1)
is_prime[0] = is_prime[1] =Falsefor i in range(2, int(max_num **0.5) +1):
if is_prime[i]:
for j in range(i * i, max_num +1, i):
is_prime[j] =Falsereturn [i for i, prime in enumerate(is_prime) if prime]
n = len(nums)
primes = sieve_primes(max(nums))
for i in range(n):
for p in reversed(primes):
if p < nums[i] and (i ==0or nums[i] - p > nums[i -1]):
nums[i] -= p
breakif i >0and nums[i] <= nums[i -1]:
returnFalsereturnTrue