Vimal
Vimal

Reputation: 87

Where does this code fails? Difference between the 2 approaches

Following is the code I used in a coding site. If I uncomment the first comment, the code works fine but if I uncomment the second code instead of first, the code produces wrong result. I am not able to figure out what's the difference between the two. Both look the same to me. Please help me find the input for which it fails using the second approach.

    Scanner input = new Scanner(System.in);
    int T = input.nextInt();

    while (T-- > 0) {
        int N = input.nextInt();
        int C = input.nextInt();
        int[] A = new int[N];

        // if I use like this code gets accepted
        // for (int i = 0; i < N; i++) A[i] = input.nextInt();

        int K = 0;

        while (C > 0 && K < N) {

            // if I use like this code produces wrong result
            // A[K] = input.nextInt();
            C -= A[K];
            K++;
        }

        String answer = "";

        if (C < 0 || K < N) answer = "No";
        else answer = "Yes";

        System.out.println(answer);
    }

    input.close();

Here's the link to the problem https://www.codechef.com/problems/LECANDY

In the first case, I am first initializing all the array elements and then performing the checking logic.

In second one, I am initializing and using the value together (control may jumps out of loop and I don't have to initialize every element)

Upvotes: 0

Views: 47

Answers (1)

Andreas
Andreas

Reputation: 159086

The second approach stops reading values once C <= 0, which means that when the outer loop starts in the next test, you're reading all the wrong values.

Example input:

2

2 1
5 6

3 4
7 8 9

Your code will read T = 2

On first iteration, you read N = 2, C = 1

With the first approach in your code, you then read A[0] = 5, A[1] = 6, so when the outer loop rolls around, you read N = 3, C = 4

However, with the second approach in your code, you read A[0] = 5, calculate C = 1 - 5 = -4 and exit the inner loop, leaving value 6, so when the outer loop rolls around, you read N = 6, C = 3, and that's all wrong.

Upvotes: 1

Related Questions