LeetCode: Non Decreasing Array Solution

1/**
2 * @param {number[]} nums
3 * @return {boolean}
4 */
5var checkPossibility = function (nums) {
6 // replace
7 for (let i = 0; i < nums.length - 1; i++) {
8 if (nums[i] > nums[i + 1]) {
9 if (nums[i] > nums[i + 2]) {
10 nums[i] = nums[i + 1]
11 } else {
12 nums[i + 1] = nums[i]
13 }
14 break
15 }
16 }
17
18 // recheck
19 for (let i = 0; i < nums.length - 1; i++) {
20 if (nums[i] > nums[i + 1]) {
21 return false
22 }
23 }
24 return true
25}

Comments

Loading comments...

Tags

leetcode

array

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Jump Game II

HoningJS

Search Posts