ChallaAjay's blog

By ChallaAjay, history, 3 hours ago, In English

Okay, here's a challenge.

The code below is supposed to find the maximum element in a non-empty array. It compiles, and it looks pretty normal.

int ans = 0;

for (int i = 0; i < n; i++) {
    if (a[i] > ans) {
        ans = a[i];
    }
}

cout << ans << '\n';

Find a valid input for which this code fails.

Rules: - Give the smallest counterexample you can find. - Explain why the output is wrong. - Bonus: fix it without changing the overall approach.

Try to find the bug before opening the comments.

Let's see who catches it first

  • Vote: I like it
  • -3
  • Vote: I do not like it

»
3 hours ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

its when the array contains negatives... like if the array a is [-1,-2]. your code outputs 0. which is wrong. cause the answer is -1. initialize the answer to a[0].

  • »
    »
    57 minutes ago, hide # ^ |
    ← Rev. 2  
    Vote: I like it 0 Vote: I do not like it

    bro the answer is -2 T_T. Edit: I'm so dumb it is maximum

    • »
      »
      »
      52 minutes ago, hide # ^ |
       
      Vote: I like it 0 Vote: I do not like it

      we are not talking about the minimum bro. its max we are talking about.

»
3 hours ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

its obvious due to ans = 0; on the case [-1] for example, set ans to INT_MIN

Funny bonus
»
113 minutes ago, hide # |
← Rev. 2  
Vote: I like it 0 Vote: I do not like it

Technically by default if the array contains long longs over the integer limit, the compiler won't tell u and make ans overflow and weird

»
39 minutes ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

you already assuming the maximum is 0 at the start . Which is only true if the array does contain atleast one element which is positive. So it fails for array which has every value less than 0.

counter example is [-1 , -2 , -3] . Your code will give answer 0 but the correct answer is actually -1