Non-decreasing Array in Python

PythonServer Side ProgrammingProgramming

Suppose we have an array with n integers, our task is to check whether it could become nondecreasing by modifying at most one element. We can define an array is non-decreasing if it satisfies this rule: array[i] <= array[i + 1] for every i (1 <= i < n). So if the array is [4,2,3], then the answer will be true. We can simply convert it to the non-decreasing array if we make the 4 to 1, then the array will be [1,2,3]

To solve this, we will follow these steps −

  • If arr has 2 or less elements, then return ture

  • ans := False

  • for i in range 0 to the number of elements in arr – 2

    • if arr[i] > arr[i + 1]

      • if ans is non 0, then return false, otherwise ans := True

      • if i > 0

        • if arr[i - 1] > arr[i + 1], then arr[i + 1] := arr[i]

  • return true

Example (Python)

Let us see the following implementation to get a better understanding −

 Live Demo

class Solution(object):
   def checkPossibility(self, nums):
      if len(nums) <=2:
         return True
      ans = False
      for i in range(len(nums)-1):
         if nums[i] > nums[i+1]:
            if ans:
               return False
            else:
               ans = True
            if i>0:
               if nums[i-1] > nums[i+1]: nums[i+1] = nums[i]
      return True
ob1 = Solution()
print(ob1.checkPossibility([4,2,3,5]))

Input

[4,2,3,5]

Output

True
raja
Published on 28-Jan-2020 14:10:37
Advertisements