Home > database >  Why is this code to check if monotonic not working?
Why is this code to check if monotonic not working?

Time:11-13

trying to find out if an array is monotonic either increasing or decreasing and return true if it is and false if it is not. this is the code I tried but it's not working can anyone tell me why?

public boolean isMonotonic()
    {
        boolean mono = false;
        boolean inc = false;
        boolean dec = false;
        for (int i = 0; i< values.length-1 ;i  )
        {
            if (values[i]<values[i 1])
            {
                inc = true;
            }
        }
        
        for (int i = 0; i< values.length-1 ;i  )
        {
            if (values[i]>values[i 1])
            {
                dec = true;
            }
        }
        if (dec || inc == true)
        {
            mono= true;
        }
        return mono;
    }

CodePudding user response:

You are checking at each set of two elements if the increasing or decreasing relationship is true. This is flawed because in many cases, you will encounter at least one set of two elements that will satisfy these conditions. So you are really just checking if at least two elements in the array are in an increasing or decreasing relationship.

What you want to do is determine the trend by checking the first two elements. Once you know the expected trend, you can iterate the array while looking for the condition where the trend isn't true. If this happens we can immediately return false. With this logic though, if we get to the end of the array we know we never violated the expected trend in which case we have a monotonic array.

This is just one solution to the problem. I'm sure there are other ways to go about doing it.

    boolean isMonotonic(int[] arr)
    {
        if (arr.length == 0)
            return false;
        if (arr.length == 1)
            return true;
        boolean increasing = arr[0] < arr[1];
        int val = arr[0];
        for (int i = 1; i < arr.length; i  )
        {
            if (increasing && val > arr[i])
                return false;
            else if (!increasing && val < arr[i])
                return false;
            val = arr[i];
        }
        return true;
    }
  • Related