관리 메뉴

솜씨좋은장씨

[leetCode] 665. Non-decreasing Array (Python) 본문

Programming/코딩 1일 1문제

[leetCode] 665. Non-decreasing Array (Python)

솜씨좋은장씨 2020. 8. 13. 23:35
728x90
반응형

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).

 

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 can't get a non-decreasing array by modify at most one element.

Constraints:

  • 1 <= n <= 10 ^ 4
  • - 10 ^ 5 <= nums[i] <= 10 ^ 5

Solution

class Solution:
    def checkPossibility(self, nums: List[int]) -> bool:
        if len(nums) < 2:
            return True
        
        cnt=0
        
        for i in range( 1, len(nums) ):
            if nums[i-1]>nums[i]:
                cnt = cnt + 1
                
                if i == 1 or nums[i-2] <= nums[i]:
                    nums[i-1] = nums[i]
                else:
                    nums[i] = nums[i-1]
                    
                if cnt > 1:
                    return False
                
        return True

 

 

SOMJANG/CODINGTEST_PRACTICE

1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.

github.com

 

Comments