From f4b32c31290d20648fb49a2d2f668ebdd15d8e5a Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Wed, 6 Nov 2024 21:41:21 +0100 Subject: [PATCH] =?UTF-8?q?kt:=20add=20=C2=AB3011.=20Find=20if=20Array=20C?= =?UTF-8?q?an=20Be=20Sorted=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit URL: https://leetcode.com/problems/find-if-array-can-be-sorted/ Signed-off-by: Matej Focko --- kt/find-if-array-can-be-sorted.kt | 46 +++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 kt/find-if-array-can-be-sorted.kt diff --git a/kt/find-if-array-can-be-sorted.kt b/kt/find-if-array-can-be-sorted.kt new file mode 100644 index 0000000..47c451b --- /dev/null +++ b/kt/find-if-array-can-be-sorted.kt @@ -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 +}