Java Solution without Altering Input


  • 0
    K
    public boolean checkPossibility(int[] nums) {
        int count = 0; // Count of changes made
        for (int i = 0;i < nums.length-1; i++) {
            // If we find a number at i+1 smaller than number at i
            if (nums[i+1] < nums[i]) { 
                if (count == 1) {
                    return false;
                }
                // If the nums[i] is the first number, we can always decrease nums[i],
                // or if the nums[i+1] is the last number, we can always increase nums[i+1].
                if ( i == 0 || i+1 == nums.length-1) { 
                    count++;    
               // Otherwise, we can decrease nums[i] to somewhere between nums[i-1] and nums[i+1], provided that nums[i-1] <= nums[i+1],
               // or we can increase nums[i] to somewhere between nums[i] and nums[i+2], provided that nums[i] <= nums[i+2].
                } else if ((nums[i-1] <= nums[i+1]) || (nums[i] <= nums[i+2])) {
                    count++;
                    // In other cases, we cannot make only one change so that it becomes a non-decreasing array
                } else {
                    return false;
                }
            }
        }
    
        return count <= 1;
    }
    

    My java solution that does not alter the input array.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.