2601. Prime Subtraction Operation #818
-
Topics: You are given a 0-indexed integer array You can perform the following operation as many times as you want:
Return true if you can make A strictly increasing array is an array whose each element is strictly greater than its preceding element. Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to break down the algorithm and adapt it to PHP syntax and functionality. The solution primarily involves the following steps:
Let's implement this solution in PHP: 2601. Prime Subtraction Operation <?php
class Solution {
/**
* @param Integer[] $nums
* @return Boolean
*/
function primeSubOperation($nums) {
$maxNum = 1000;
$primes = $this->sieveEratosthenes($maxNum);
$prevNum = 0;
foreach ($nums as &$num) {
// Find the largest prime `p` that makes `num - p > prevNum`
$prime = $this->findLargestPrimeLessThan($primes, $num - $prevNum);
if ($prime !== null) {
$num -= $prime;
}
// Check if the current number is greater than the previous number
if ($num <= $prevNum) {
return false;
}
$prevNum = $num;
}
return true;
}
/**
* Helper function to generate all primes up to n using Sieve of Eratosthenes
*
* @param $n
* @return array
*/
private function sieveEratosthenes($n) {
$isPrime = array_fill(0, $n + 1, true);
$isPrime[0] = $isPrime[1] = false;
$primes = [];
for ($i = 2; $i <= $n; $i++) {
if ($isPrime[$i]) {
$primes[] = $i;
for ($j = $i * $i; $j <= $n; $j += $i) {
$isPrime[$j] = false;
}
}
}
return $primes;
}
/**
* Helper function to find the largest prime less than a given limit using binary search
*
* @param $primes
* @param $limit
* @return mixed|null
*/
private function findLargestPrimeLessThan($primes, $limit) {
$left = 0;
$right = count($primes) - 1;
while ($left <= $right) {
$mid = $left + (int)(($right - $left) / 2);
if ($primes[$mid] < $limit) {
$left = $mid + 1;
} else {
$right = $mid - 1;
}
}
return $right >= 0 ? $primes[$right] : null;
}
}
// Example usage:
$solution = new Solution();
echo $solution->primeSubOperation([4, 9, 6, 10]) ? 'true' : 'false'; // Output: true
echo $solution->primeSubOperation([6, 8, 11, 12]) ? 'true' : 'false'; // Output: true
echo $solution->primeSubOperation([5, 8, 3]) ? 'true' : 'false'; // Output: false
?> Explanation:
Complexity Analysis
This solution will return |
Beta Was this translation helpful? Give feedback.
We need to break down the algorithm and adapt it to PHP syntax and functionality. The solution primarily involves the following steps:
nums
(1000).nums
, check if we can subtract a prime to make the array strictly increasing.Let's implement this solution in PHP: 2601. Prime Subtraction Operation