Check whether an array can made strictly increasing by modifying at most once

Given an array of integers, write a function to determine whether the array could become non-decreasing by modifying at most 1 element.

For example, given the array [10, 5, 7], you should return true, since we can modify the 10 into a 1 to make the array non-decreasing.

Given the array [10, 5, 1], you should return false, since we can't modify any one element to get a non-decreasing array.

Example:

Input:  arr = [10,5,7]
Output: true

Approach

C++

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

bool checkNonDecreasingArray(vector<int&nums)
{
    int n = nums.size(), cnt = 0;
    for (int i = 0i < n - 1 && cnt <= 1i++)
    {
        if (nums[i] > nums[i + 1])
        {
            if (i > 0)
            {
                if (nums[i - 1] <= nums[i + 1])
                    nums[i] = nums[i - 1];
                else
                    nums[i + 1] = nums[i];
            }
            ++cnt;
        }
    }
    return cnt <= 1;
}

int main()
{
    vector<intnums = {1057};
    if (checkNonDecreasingArray(nums))
        cout << "true";
    else
        cout << "false";

    return 0;
}


No comments:

Post a Comment