kt: add «2601. Prime Subtraction Operation»

URL:	https://leetcode.com/problems/prime-subtraction-operation/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-11-12 00:03:52 +01:00
parent 97b79b8025
commit d2aca8d88f
No account linked to committer's email address

View file

@ -0,0 +1,36 @@
class Solution {
private fun getPrimes(nums: IntArray): BooleanArray {
val primes = BooleanArray(1 + nums.max()) { true }
primes[1] = false
(2..sqrt(primes.size.toDouble()).toInt())
.asSequence()
.filter { primes[it] }
.forEach { i ->
(i * i..<primes.size step i).forEach { j ->
primes[j] = false
}
}
return primes
}
fun primeSubOperation(nums: IntArray): Boolean {
val primes = getPrimes(nums)
var (current, i) = 1 to 0
while (i < nums.size) {
val difference = nums[i] - current
if (difference < 0) {
return false
}
if (primes[difference] || difference == 0) {
i += 1
}
current += 1
}
return true
}
}