Given a 0-indexed integer array nums, return true _if it can be madestrictly increasing after removing exactly one element, or _falseotherwise. If the array is already strictly increasing, returntrue.
The array nums is strictly increasing if nums[i - 1] < nums[i] for each index (1 <= i < nums.length).
Input: nums =[1,2,_10_ ,5,7]Output: trueExplanation: By removing 10 at index 2 from nums, it becomes [1,2,5,7].[1,2,5,7]is strictly increasing, so returntrue.
Input: nums =[2,3,1,2]Output: falseExplanation:
[3,1,2]is the result of removing the element at index 0.[2,1,2]is the result of removing the element at index 1.[2,3,2]is the result of removing the element at index 2.[2,3,1]is the result of removing the element at index 3.No resulting array is strictly increasing, so returnfalse.
If the array is not strictly increasing, there must be at most one place where nums[i-1] >= nums[i]. We can try removing either nums[i-1] or nums[i] and check if the result is strictly increasing.
publicclassSolution {
publicbooleancanBeIncreasing(int[] nums) {
for (int i = 1; i < nums.length; i++) {
if (nums[i-1]>= nums[i]) {
return isStrict(nums, i-1) || isStrict(nums, i);
}
}
returntrue;
}
privatebooleanisStrict(int[] nums, int skip) {
int prev =-1;
for (int i = 0; i < nums.length; i++) {
if (i == skip) continue;
if (prev !=-1 && nums[prev]>= nums[i]) returnfalse;
prev = i;
}
returntrue;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
funcanBeIncreasing(nums: IntArray): Boolean {
funisStrict(skip: Int): Boolean {
var prev = -1for (i in nums.indices) {
if (i == skip) continueif (prev != -1&& nums[prev] >= nums[i]) returnfalse prev = i
}
returntrue }
for (i in1 until nums.size) {
if (nums[i-1] >= nums[i]) {
return isStrict(i-1) || isStrict(i)
}
}
returntrue}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
defcanBeIncreasing(nums):
defis_strict(skip):
prev =Nonefor i in range(len(nums)):
if i == skip:
continueif prev isnotNoneand nums[prev] >= nums[i]:
returnFalse prev = i
returnTruefor i in range(1, len(nums)):
if nums[i-1] >= nums[i]:
return is_strict(i-1) or is_strict(i)
returnTrue