Obviously, it can use dynamic programming.
dp[i] represents the minimum number needs to delete to make previous i th elements in nums beautiful.
The transfering is easy, just need to consider if the new position is even or odd. If it is even just add 1, after the whole process, check the final length of nums is even or odd to ensure the length is legal too.
class Solution {
public:
int minDeletion(vector<int>& nums) {
int len = nums.size();
if(len == 1)return 1;
int dp[100005];
memset(dp, 0, sizeof(dp));
for(int i = 0; i < len - 1; i++){
if(i == 0)dp[i] = (nums[i] == nums[i + 1]);
else if((i-dp[i - 1])%2){
dp[i] = dp[i - 1];
}else{
dp[i] = dp[i - 1] + (nums[i] == nums[i + 1]);
}
}
if((len - dp[len - 2])%2)return dp[len - 2] + 1;
return dp[len - 2];
}
};
as the dp only depends on the i - 1, we can use one varible to replace the whole dp array.
class Solution {
public:
int minDeletion(vector<int>& nums) {
int len = nums.size();
if(len == 1)return 1;
int res;
for(int i = 0; i < len - 1; i++){
if(i == 0)res = (nums[i] == nums[i + 1]);
else if((i-res)%2){
continue;
}else{
res += (nums[i] == nums[i + 1]);
}
}
if((len - res)%2)return res + 1;
return res;
}
};