A
A
Aleksey Kuzmin2020-04-15 15:56:35
Java
Aleksey Kuzmin, 2020-04-15 15:56:35

Sequential units - why does one of the solutions not work?

There is a simple task on Yandex.Interview "B. Consecutive Units".
Link https://contest.yandex.ru/contest/8458/problems/B/

made two solutions on Java 8
The first one passes all tests on Yandex successfully.

public class Application
{
    public static void main(String[] args) throws Exception {
        BufferedReader r = new BufferedReader(new FileReader("input.txt"));

        int size = Integer.valueOf(r.readLine());
        int[] sequence = new int[size + 1];
        for (int i = 1; i <= size; i++) {
            sequence[i] = Integer.valueOf(r.readLine());
        }

        System.out.println(longestSequence(sequence));
    }

    public static int longestSequence(int[] vector)
    {
        int maxLength = 0;
        int currentLength = 0;

        for (int i = 0; i <= vector.length - 1; i++)
        {
            if (vector[i] == 1)
            {
                currentLength++;
                maxLength = (currentLength > maxLength) ? currentLength : maxLength;
            }
            else
            {

                currentLength = 0;
            }
        }

        return maxLength;
    }
}


the second solution is shorter.
But only the first few tests are successful. Wrong answer verdict.
public class Application
{
   public static void main(String[] args) throws Exception {
        BufferedReader r = new BufferedReader(new FileReader("input.txt"));

        int maxLength = 0;
        int currentLength = 0;
        int value;
        String line;

        while ((line = r.readLine()) != null)
        {
            try {
                value = Integer.valueOf(line);
                if (value == 1) {
                    currentLength++;
                    maxLength = (currentLength > maxLength) ? currentLength : maxLength;
                } else {
                    currentLength = 0;
                }
            }
            catch (Exception e)
            {

            }
        }

        System.out.println(maxLength);
    }
}


According to my tests, everything is OK in both solutions.

Yes, in the second solution, I omitted the use of the first number n (number of vector elements).
In what situation does this begin to affect the result? Tell me plz

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question