Here, We see Non-decreasing Array LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.
List of all LeetCode Solution
![Non-decreasing Array LeetCode Solution](https://i0.wp.com/totheinnovation.com/wp-content/uploads/2024/02/LeetCode-Problem-Solution.png?resize=200%2C200&ssl=1)
Non-decreasing Array LeetCode Solution
Table of Contents
Problem Statement
Given an array nums with n integers, your task is to check if it could become non-decreasing by modifying at most one 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).
Example 1:
Input: nums = [4,2,3]
Output: true
Explanation: You could modify the first 4 to 1 to get a non-decreasing array.
Example 2:
Input: nums = [4,2,1]
Output: false
Explanation: You cannot get a non-decreasing array by modifying at most one element.
Non-decreasing Array Leetcode Solution C++
class Solution {
public:
bool checkPossibility(vector<int>& nums)
{
for(int i=0;i<nums.size()-1;i++)
{
if(nums[i]>nums[i+1])
{
if(i-1>=0&&nums[i-1]>nums[i+1])
{
nums[i+1]=nums[i];
}
else
{
nums[i]=nums[i+1];
}
break;
}
}
for(int i=0;i<nums.size()-1;i++)
{
if(nums[i]>nums[i+1])
{
return false;
}
}
return true;
}
};
Code language: PHP (php)
Non-decreasing Array Leetcode Solution Java
class Solution {
public boolean checkPossibility(int[] nums) {
for (int i = 1, err = 0; i < nums.length; i++)
if (nums[i] < nums[i-1])
if (err++ > 0 || (i > 1 && i < nums.length - 1 && nums[i-2] > nums[i] && nums[i+1] < nums[i-1]))
return false;
return true;
}
}
Code language: PHP (php)
Non-decreasing Array Solution JavaScript
var checkPossibility = function(nums) {
for (let i = 1, err = 0; i < nums.length; i++)
if (nums[i] < nums[i-1])
if (err++ || (i > 1 && i < nums.length - 1 && nums[i-2] > nums[i] && nums[i+1] < nums[i-1]))
return false
return true
};
Code language: JavaScript (javascript)
Non-decreasing Array Solution Python
class Solution(object):
def checkPossibility(self, nums):
err = 0
for i in range(1, len(nums)):
if nums[i] < nums[i-1]:
if err or (i > 1 and i < len(nums) - 1 and nums[i-2] > nums[i] and nums[i+1] < nums[i-1]):
return False
err = 1
return True
Code language: HTML, XML (xml)