665.non-decreasing-array.go 309 B

123456789101112131415161718
  1. func checkPossibility(nums []int) bool {
  2. n := len(nums)
  3. if n < 3 {
  4. return true
  5. }
  6. cnt := 0
  7. for i := 1; i < n && cnt <= 1; i++ {
  8. if nums[i] < nums[i-1] {
  9. cnt++ // Greedy
  10. if i < 2 || nums[i-2] <= nums[i] {
  11. nums[i-1] = nums[i]
  12. } else {
  13. nums[i] = nums[i-1]
  14. }
  15. }
  16. }
  17. return cnt <= 1
  18. }