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:
parent
97b79b8025
commit
d2aca8d88f
1 changed files with 36 additions and 0 deletions
36
kt/prime-subtraction-operation.kt
Normal file
36
kt/prime-subtraction-operation.kt
Normal 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
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue