Skip to content

2216. Minimum Deletions to Make Array Beautiful 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
 public:
  int minDeletion(vector<int>& nums) {
    int ans = 0;

    for (int i = 0; i + 1 < nums.size(); ++i)
      // i - ans := the index after deletion
      if (nums[i] == nums[i + 1] && (i - ans) % 2 == 0)
        ++ans;

    return ans + ((nums.size() - ans) & 1);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
  public int minDeletion(int[] nums) {
    int ans = 0;

    for (int i = 0; i + 1 < nums.length; ++i)
      // i - ans := the index after deletion
      if (nums[i] == nums[i + 1] && (i - ans) % 2 == 0)
        ++ans;

    return ans + (((nums.length - ans) & 1) == 1 ? 1 : 0);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def minDeletion(self, nums: list[int]) -> int:
    ans = 0

    for i in range(len(nums) - 1):
      # i - ans := the index after deletion
      if nums[i] == nums[i + 1] and (i - ans) % 2 == 0:
        ans += 1

    # Add one if the length after deletion is odd
    return ans + ((len(nums) - ans) & 1)