Taken from DailyCodingProblem
Given an array of integers, write a function to determine whether the array could become non-decreasing by modifying at most 1
element.
For example, given the array [10, 5, 7]
, you should return true
, since we can modify the 10
into a 1
to make the array non-decreasing.
Given the array [10, 5, 1]
, you should return false
, since we can’t modify any one element to get a non-decreasing array.
This is the answer I came up with:
function couldBeNonDecreasing ( arr : Array < number > ): boolean {
// As long as the first element is larger than the second,
// and the second larger than the third, always return false
if ( arr [ 0 ] > arr [ 1 ] && arr [ 1 ] > arr [ 2 ]) {
return false
}
// Otherwise, return true
return true
}
If at most one element can be changed, then the maximum array length is always 3
. Also, non-decreasing means the array items are less than or equal to each other in ascending order, i.e. arr[0] <= arr[1] && arr[1] <= arr[2]
Solution tested in REPL: https://www.typescriptlang.org/play?ssl=10&ssc=2&pln=1&pc=1#code/GYVwdgxgLglg9mABBOIA2ATAQgUwHIIAiOEATjgIYDOMYA5gBQWmkBciAgixQJ4A8YEAFsARjlIA+AJTsRcOGkpIA3gFgAUIkQB6bZyqI0COomqIoACxyJgMUlSiIcioTjCOYBtMzrjzFiiRLayoSBAwAGg0tXVMwDH8QsPjDHz9LQMT-O0jTNAB3XgNyKBBSJGAKNFDoxBhgRCYWAG0ABgBdRAlTFoBGToAyAZ7SZv6ukeaAJnapRDVNLUQSsoqqmsWAX1qtWtiAeWDSfM8cCOWcUvLzUhAcWpXrqFv79W31DRQwKgUcADojIxaih0Nh8EQSORqLRGGNWucAKznfpSc6xSrVV5aEGYXAEMDEMiUGj0BhwxHnADsszRemed0QzQALBTENTgahceCCZDiTCyb1WSjaTcGWNkYh+hzQXiIUToaTmgBOZEAZmRNJ0dJejJVkvVkqZ7WlXPxhKhJNhBsFiA6qK1NnWrykGiAA