File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed
src/main/kotlin/g3401_3500/s3469_find_minimum_cost_to_remove_array_elements Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change 1+ package g3401_3500.s3469_find_minimum_cost_to_remove_array_elements
2+
3+ // #Medium #2025_03_06_Time_51_ms_(100.00%)_Space_46.26_MB_(100.00%)
4+
5+ import kotlin.math.max
6+ import kotlin.math.min
7+
8+ class Solution {
9+ fun minCost (nums : IntArray ): Int {
10+ var nums = nums
11+ var n = nums.size
12+ if (n % 2 == 0 ) {
13+ nums = nums.copyOf(++ n)
14+ }
15+ val dp = IntArray (n)
16+ var j = 1
17+ while (j < n - 1 ) {
18+ var cost1: Int = INF
19+ var cost2: Int = INF
20+ val max = max(nums[j], nums[j + 1 ])
21+ for (i in 0 .. < j) {
22+ cost1 =
23+ min(cost1, dp[i] + max(nums[i], nums[j + 1 ]))
24+ cost2 = min(cost2, dp[i] + max(nums[i], nums[j]))
25+ dp[i] + = max
26+ }
27+ dp[j] = cost1
28+ dp[j + 1 ] = cost2
29+ j + = 2
30+ }
31+ var result: Int = INF
32+ for (i in 0 .. < n) {
33+ result = min(result, dp[i] + nums[i])
34+ }
35+ return result
36+ }
37+
38+ companion object {
39+ private const val INF = 1e9.toInt()
40+ }
41+ }
You can’t perform that action at this time.
0 commit comments