C Min/Max Bug: Why Sample Tests Pass But Judge Gives Wrong Answer

Your C solution passes every sample test case—yet submitting it to an online judge returns Wrong Answer.

One of the most common causes is initializing max_val = 0 (or min_val = 0), which silently breaks whenever all inputs are negative (or all positive).

1. The Buggy Code

#include <stdio.h>

int main(void) {
    int n, x;
    int max_val = 0;  // BUG: fails if all inputs are negative!

    scanf("%d", &n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &x);
        if (x > max_val) max_val = x;
    }

    printf("%d\n", max_val);
    return 0;
}

Counterexample Input: 3 followed by -8 -2 -4

Expected: -2  |  Actual: 0 (not even in the input!)

2. The Fix: Initialize With the First Input Value

#include <stdio.h>

int main(void) {
    int n, x;
    if (scanf("%d", &n) != 1 || n <= 0) return 0;

    scanf("%d", &x);
    int min_val = x;
    int max_val = x;

    for (int i = 1; i < n; i++) {
        scanf("%d", &x);
        if (x < min_val) min_val = x;
        if (x > max_val) max_val = x;
    }

    printf("%d %d\n", min_val, max_val);
    return 0;
}

Verified Outputs:

  • Input -8 -2 -4 → Output -8 -2
  • Input 7 (single element) → Output 7 7

Comments

Popular posts from this blog

Java Integer Overflow: Why Adding Positive Numbers Gives a Negative Sum

C strtol Validation: Why atoi("abc") Returns 0 and How to Fix It

Why Excel Breaks Your Python CSV (1-Word UTF-8 BOM Fix)