From 1db0649431671e16ae1d4ce733db128a0e8006bc Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Thu, 31 Oct 2024 00:09:24 +0100 Subject: [PATCH] =?UTF-8?q?kt:=20add=20=C2=AB1671.=20Minimum=20Number=20of?= =?UTF-8?q?=20Removals=20to=20Make=20Mountain=20Array=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit URL: https://leetcode.com/problems/minimum-number-of-removals-to-make-mountain-array/ --- ...mber-of-removals-to-make-mountain-array.kt | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 kt/minimum-number-of-removals-to-make-mountain-array.kt diff --git a/kt/minimum-number-of-removals-to-make-mountain-array.kt b/kt/minimum-number-of-removals-to-make-mountain-array.kt new file mode 100644 index 0000000..e74de4c --- /dev/null +++ b/kt/minimum-number-of-removals-to-make-mountain-array.kt @@ -0,0 +1,38 @@ +class Solution { + private fun longestIncreasing(nums: IntArray): IntArray { + val found = + IntArray(nums.size) { + 1 + } + + nums.indices + .flatMap { i -> + (0..i - 1) + .reversed() + .map { j -> i to j } + } + .filter { (i, j) -> nums[i] > nums[j] } + .forEach { (i, j) -> + found[i] = listOf(found[i], 1 + found[j]).max() + } + + return found + } + + fun minimumMountainRemovals(nums: IntArray): Int { + val increasing = longestIncreasing(nums) + + nums.reverse() + val decreasing = longestIncreasing(nums) + decreasing.reverse() + + return increasing + .zip(decreasing) + .filter { (l, r) -> + l > 1 && r > 1 + } + .minOf { (l, r) -> + nums.size - l - r + 1 + } ?: nums.size + } +}