My poor solution, failed twice in an easy question

  • 0

    The problem is well described. However, made several mistakes listing examples and failed twice to come up with the solution. It records two number prior to the current one and judge if the current one violates the rule. If it does, then we can fix it using greedy method. If the fix has already happened, then return false.

    class Solution {
        public boolean checkPossibility(int[] nums) {
            if (nums == null || nums.length == 0) return false;
            boolean flag = false;
            int prevMax = Integer.MIN_VALUE, max = Integer.MIN_VALUE;
            for (int num : nums) {
                if (num >= max) {
                    prevMax = max;
                    max = num;
                } else {
                    if (flag) return false;
                    if (num >= prevMax) max = num;
                    flag = true;
            return true;

Log in to reply

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