Leetcode 1909. Remove One Element to Make the Array Strictly Increasing
You are given a 0-indexed integer array nums
. You need to determine if it is possible to remove exactly one element from the array such that the resulting array is strictly increasing.
An array nums
is strictly increasing if nums[i] < nums[i+1]
for every index i
where 0 <= i < nums.length - 1
.
Return true
if it is possible to remove one element from the array to make it strictly increasing, otherwise return false
.
Example:
Input: nums = [1,2,10,5,7]
Output: true
#include <vector>
using namespace std;
class Solution {
public:
bool canBeIncreasing(vector<int>& nums) {
int n = nums.size();
// Track the number of violations
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 nums[i-1] or nums[i] could solve the problem
if (i > 1 && nums[i] <= nums[i-2] && i < n-1 && nums[i+1] <= nums[i-1]) {
return false;
}
}
}
return true;
}
};
nums[i-1] >= nums[i]
.false
immediately, as removing one element won’t be sufficient.(nums[i-1], nums[i])
:
nums[i-1]
or nums[i]
could potentially fix the array to make it strictly increasing.nums[i] <= nums[i-2]
and nums[i+1] <= nums[i-1]
to see if removing one of the elements would lead to a potential fix.This ensures the algorithm is efficient even for larger inputs.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?