#2601
Prime Subtraction Operation
MediumArrayMathBinary SearchGreedyNumber TheoryGreedyArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Instead of checking all primes for each element, we can directly calculate the largest prime we can subtract to ensure the array is strictly increasing. This reduces unnecessary checks and speeds up the process.
⚙️
Algorithm
5 steps- 1Step 1: Generate a list of all prime numbers less than 1000.
- 2Step 2: Iterate through the nums array from the second element to the last.
- 3Step 3: For each element, calculate the minimum value it must be greater than (the previous element).
- 4Step 4: Find the largest prime less than the current element that can be subtracted to meet the condition.
- 5Step 5: If no such prime exists, return false. If all elements can be adjusted successfully, return true.
solution.py15 lines
1# Full working Python code
2from sympy import primerange
3
4
5def can_make_increasing(nums):
6 primes = list(primerange(1, 1000))
7 for i in range(1, len(nums)):
8 required = nums[i - 1] + 1
9 for p in reversed(primes):
10 if nums[i] - p >= required:
11 nums[i] -= p
12 break
13 else:
14 return False
15 return Trueℹ
Complexity note: The time complexity is O(n) because we iterate through the nums array once and check primes in a more efficient manner, reducing unnecessary checks.
- 1Understanding the properties of prime numbers can help optimize the solution.
- 2The order of operations matters; always consider the previous element when adjusting the current one.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.