Java solution without modifying array


  • 0
    K

    We can solve this in place with two extra variables

    class Solution {
        public boolean checkPossibility(int[] nums) {
            int n = 0;
            int pprev = Integer.MIN_VALUE, prev = nums[0];
            
            for(int i=1; i<nums.length; i++){
                if(nums[i]>=prev){
                    prev = nums[i];
                    pprev = nums[i-1];
                }
                else if(nums[i]>=pprev){
                    prev = nums[i]; //update prev alone, current prev is the anomaly
                    n++;
                }
                else{
                    //nums[i] is less than prev and pprev
                    n++;
                }
                
                if(n>1)
                    return false;
            }
            
            return true;
        }
    }
    

Log in to reply
 

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