Given an integer array arr[] of size n, the task is to check if the given array can be made strictly increasing after removing at most one element from the array. Return true if it is possible to make the given array strictly increasing else return false. Note: If the given array is already strictly increasing then simply return true.
- A strictly increasing array means that for every nums[i] and nums[i + 1], the relationship nums[i] < nums[i + 1] holds.
Example:
Input: arr[] = {1, 2, 12, 5, 7}
Output: true
Explanation: By removing 12 from index 2, the array becomes {1, 2, 5, 7}
which is strictly increasing.
Input: arr[] = {1, 4, 5, 3, 2}
Output: false
Explanation: By removing any element of the array it is not possible to make
it strictly increasing.
Input: arr[] = {1, 2, 2, 5, 5}
Output: false
Approach 1: Brute Force.
//C++ Brute Force Approach to check strictly increasing array #include<iostream> #include <vector> using namespace std; //helper function to check if the array is //strictly increasing or not bool isStrictlyIncreasing(vector<int>& nums) { int n = nums.size(); bool isIncreasing = true; for (int i = 1; i < n; i++) { if (nums[i] <= nums[i - 1]) { isIncreasing = false; break; } } return isIncreasing; } bool canBeIncreasing(vector<int>& nums) { int n = nums.size(); for (int i = 0; i < n; i++) { int removedElement = nums[i]; // Simulate removing the element nums.erase(nums.begin() + i); //calling helper function to check if (isStrictlyIncreasing(nums)) { return true; } // Put back the removed element nums.insert(nums.begin() + i, removedElement); } return false; } int main(){ vector<int> nums{1, 2, 12, 5, 7}; if(canBeIncreasing(nums)) cout<<"True"; else cout<<"False"; return 0; }
True
Approach 2: Optimized Approach.
- If the current element is greater than the element before the previous element (nums[i] > nums[i - 2]), we remove the current element by setting it equal to the previous element.
- Otherwise, we remove the previous element by setting it equal to the current element.
//C++ Optimized Approach to check strictly increasing array #include<iostream> #include <vector> using namespace std; //function to check strictly increasing bool canBeIncreasing(vector<int>& nums) { int n = nums.size(); // Count of violating elements int count = 0; for (int i = 1; i < n; i++) { if (nums[i] <= nums[i - 1]) { count++; if (count > 1) { return false; } // Check if removing the current element makes
//the array strictly increasing if (i == 1 || nums[i] > nums[i - 2]) { nums[i - 1] = nums[i]; } else { nums[i] = nums[i - 1]; } } } return true; } int main(){ vector<int> nums{1, 2, 12, 5, 7}; if(canBeIncreasing(nums)) cout<<"True"; else cout<<"False"; return 0; }
True