N
N
Nikita Kudinov2018-12-06 21:50:17
Java
Nikita Kudinov, 2018-12-06 21:50:17

Finding the number of descending spans in Java?

There is a searchIntervals method, but for some reason it works every other time. Can you suggest where is the error?
I call the method twice with this data:

  1. 3, 5, 6, 3, 2, 1, 5, 1, 8 - returns 3 when it should be 2
  2. 3, 2, 2, 8, 3, 8, 9, 4, 7, 2, 9, 2 - returns 5, everything is correct
public static int searchIntervals(int[] nums) {
        int sum = 0;

        for (int i = 0; i < nums.length - 1; i++) {
            if (nums[i] > nums[i + 1]) {
                sum++;
                if (i + 2 <= nums.length - 1) {
                    if (nums[i + 1] > nums[i + 2]) {
                        i++;
                    }
                }
            }
        }

        return sum;
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikita Kudinov, 2018-12-06
@Nikita_Kudinov

Decided like this:

private static int searchIntervals(int[] nums) {
        int sum = 0;

        for (int i = 0; i < nums.length - 1; i++) {
            if (nums[i] > nums[i + 1]) {
                sum++;
                int cntr = 0;
                for (int h = i+1; h < nums.length - 1 - i; h++) {
                    cntr++;
                    if (nums[h] > nums[h + 1]) continue;
                    else break;
                }
                i+=cntr;
            }
        }

        return sum;
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question