kt: add «3011. Find if Array Can Be Sorted»

URL:	https://leetcode.com/problems/find-if-array-can-be-sorted/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-11-06 21:41:21 +01:00
parent bddc4f48dd
commit f4b32c3129
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,46 @@
class Solution {
private fun min(
x: Int,
y: Int,
): Int = listOf(x, y).min()
private fun max(
x: Int,
y: Int,
): Int = listOf(x, y).max()
private data class State(
val prevMax: Int,
val bitCount: Int,
val min: Int,
val max: Int,
) {
val sortable: Boolean
get() = min >= prevMax
private fun getSegmentMaximum(
prevMax: Int,
min: Int,
max: Int,
): Int =
if (min < prevMax) {
Int.MAX_VALUE
} else {
max
}
fun update(num: Int): State =
if (bitCount == num.countOneBits()) {
State(prevMax, bitCount, min(min, num), max(max, num))
} else {
State(getSegmentMaximum(prevMax, min, max), num.countOneBits(), num, num)
}
}
private fun getInitialState(num: Int): State = State(Int.MIN_VALUE, num.countOneBits(), num, num)
fun canSortArray(nums: IntArray): Boolean =
nums.fold(getInitialState(nums[0])) { acc, it ->
acc.update(it)
}.sortable
}