Java - O(n) without changing input


  • 0
    S
    class Solution {
        public boolean checkPossibility(int[] nums) {
            if(nums.length <2) return true;
            int maxsofar = Integer.MIN_VALUE;
            int count =0;
            for(int i=0; i<nums.length; i++){
                if(nums[i]>=maxsofar){
                    maxsofar = nums[i];
                } else{
                    // if A[i]>=A[i-2] => A[i-1]=A[i-2] . otherwise, A[i]=A[i-2]
                    maxsofar = i>1 ? (nums[i]>=nums[i-2] ? nums[i] : nums[i-1]): nums[i]; 
                    count++;
                    if(count>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.