problems: add „659. Split Array into Consecutive Subsequences“
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
1ccb92b8a7
commit
6eb2f09892
1 changed files with 37 additions and 0 deletions
37
problems/split-array-into-consecutive-subsequences.kt
Normal file
37
problems/split-array-into-consecutive-subsequences.kt
Normal file
|
@ -0,0 +1,37 @@
|
||||||
|
class Solution {
|
||||||
|
private fun getFrequencies(nums: IntArray): MutableMap<Int, Int> {
|
||||||
|
val freqs = mutableMapOf<Int, Int>()
|
||||||
|
|
||||||
|
nums.forEach {
|
||||||
|
freqs[it] = 1 + freqs.getOrDefault(it, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
return freqs
|
||||||
|
}
|
||||||
|
|
||||||
|
fun isPossible(nums: IntArray): Boolean {
|
||||||
|
val frequencies = getFrequencies(nums)
|
||||||
|
val sortedNumbers = frequencies.keys.toList().sorted()
|
||||||
|
|
||||||
|
sortedNumbers.forEach {
|
||||||
|
while (frequencies[it]!! > 0) {
|
||||||
|
var last = 0
|
||||||
|
var j = it
|
||||||
|
var k = 0
|
||||||
|
|
||||||
|
while (frequencies.getOrDefault(j, 0) >= last) {
|
||||||
|
last = frequencies[j]!!
|
||||||
|
frequencies[j] = frequencies[j]!! - 1
|
||||||
|
|
||||||
|
j++
|
||||||
|
k++
|
||||||
|
}
|
||||||
|
if (k < 3) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue