39ms C++ solution, O(n) using max and min while traversing, without modifying input array


  • 0
    I
    class Solution {
    public:
        bool checkPossibility(vector<int>& nums) {
            int count1 = 0, count2=0, max=nums[0],min=nums.back(),n=nums.size();
            for (int i=0;i<n;i++) {
                if (nums[i]>max) {
                    max = nums[i];
                }
                else if (nums[i]<max) {
                    count1++;
                }
                if (nums[n-i-1]<min) {
                    min = nums[n-i-1];
                }
                else if (nums[n-i-1]>min) {
                    count2++;
                }
            }
            return count1<2 or count2<2;
        }
    };
    

Log in to reply
 

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