LeetCode Entry
3507. Minimum Pair Removal to Sort Array I
Sort by removing lowest sum pairs
3507. Minimum Pair Removal to Sort Array I easy blog post substack youtube

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/1245
Problem TLDR
Sort by removing lowest sum pairs #easy
Intuition
Simulate the process.
Approach
- just create a new array each time
- or in Rust we can actually remove by index in-place
Complexity
-
Time complexity: \(O(n^2)\) n^2log(n) for golfing in Kotlin
-
Space complexity: \(O(n)\)
Code
// 76ms
fun minimumPairRemoval(l: IntArray): Int {
val l = l.toList()
if (l == l.sorted()) return 0
val j = (1..<l.size).minBy { l[it-1] + l[it] }
return 1 + minimumPairRemoval((l.take(j-1) + (l[j-1]+l[j]) + l.drop(j+1)).toIntArray())
}
// 0ms
pub fn minimum_pair_removal(mut l: Vec<i32>) -> i32 {
(0..).find(|_| {
let ok = l.windows(2).all(|w| w[0] <= w[1]);
if let Some(j) = (1..l.len()).min_by_key(|&i| l[i-1] + l[i]) { l[j-1] += l[j]; l.remove(j); }
ok
}).unwrap()
}