Remove One Element to Make the Array Strictly Increasing

Given a 0-indexed integer array nums, return true if it can be made strictly increasing after removing exactly one element, or false otherwise. If the array is already strictly increasing, return true.

The array nums is strictly increasing if nums[i - 1] < nums[i] for each index (1 <= i < nums.length).

Example 1:

Input: nums = [1,2,10,5,7]
Output: true
Explanation: By removing 10 at index 2 from nums, it becomes [1,2,5,7].
[1,2,5,7] is strictly increasing, so return true.

Example 2:

Input: nums = [2,3,1,2]
Output: false
Explanation:
[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 return false.

Approach

C++

#include <bits/stdc++.h>
using namespace std;

bool canBeIncreasing(vector<int&nums)
{

    int n = nums.size();

    int max1 = nums[0];

    bool flag = false;
    for (int i = 1i < ni++)
    {
        if (nums[i] <= max1)
        {
            if (flag == true)
            {
                return false;
            }
            flag = true;
            if (i == 1 || nums[i] > nums[i - 2])
                max1 = nums[i];
        }
        else
            max1 = nums[i];
    }
    return true;
}

int main()
{
    vector<intnums = {121057};

    if (canBeIncreasing(nums))
        cout << "true\n";
    else
        cout << "false\n";

    return 0;
}


No comments:

Post a Comment