1. Description
Given an array, find whether it could become non-descreasing by modifying at most 1 element.
2. Solution
Traverse the array, if there is an element bigger that the element next to it. Modify the current element's value to the next element or modify the next element's value to the current element's value.
If one of the conditions can make the array non- descreasing, then return true.
3. Code
bool checkPossibility(vector<int>& nums) {
int cnt = 0;
int n = nums.size();
for(int i=0;i<n-1;i++){
if(nums[i]>nums[i+1]){
int org = nums[i];
nums[i]=nums[i+1];
if( check(nums) )
return true;
else{
nums[i]=org;
nums[i+1] = org;
if( check(nums) )
return true;
else return false;
}
}
}
return true;
}
bool check(vector<int> nums){
int n = nums.size();
for(int i=0;i<n-1;i++){
if(nums[i]>nums[i+1])
return false;
}
return true;
}