Menu Close

Check if array could become Non – Decreasing array.

Given an array nums with n integers, your task is to check if it could become non-decreasing by modifying at most 1 element. We define an array is non-decreasing if nums[i] <= nums[i + 1] holds for every i (0-based) such that (0 <= i <= n – 2).

Input : [4,2,3]
Output : True
(Explanation: You could modify the first 4 to 1 to get a non-decreasing array.)

Input : [4,2,1]
Output : False
(Explanation: You can’t get a non-decreasing array by modifying at most one element.)

Arr=list(map(int,input('Enter an array of n integers : ').split(' ')))
P=0
i=0
while i<len(Arr):
    if i+1<len(Arr) and P<len(Arr):
        if Arr[i]<=Arr[i+1]:
            i+=1
            continue
        else:
            if i==0:
                Arr[i]=Arr[i+1]-1
                P+=1
                continue
            Arr[i+1]=Arr[i]+1 if(Arr[i]>Arr[i+1]) else Arr[i-1]+1
            P+=1
            continue
    else:
        break
    i+=1
if P>1:
    print('False')
else:
    print('True')

Input_1:
Enter an array of n integers : 4 2 3
Output:
True


Input_2:
Enter an array of n integers : 4 2 1
Output:
False


Input_3:
Enter an array of n integers : 6 7 8 9 1 11
Output:
True


Input_4:
Enter an array of n integers : 6 7 8 9 1 1 11
Output:
False


Input_5:
Enter an array of n integers : 6 7 8 1 1 11
Output:
False


Input_6:
Enter an array of n integers : 4 2 8
Output:
True


Sample Outputs Executed

Executed Using Linux Terminal(Python3)

More Q