Problem 1 - Javelin

Here, we will discuss the solution to Javelin from AIO 2024.

Summary

N students participated in a javelin throwing event. A student is a current leader if they threw further than everyone before them. How many different current leaders were there during the competition?

Solution

We consider the students one at a time while storing the furthest distance that a student has thrown so far (we will call this value best_throw). There are two cases:

  1. If Di > best_throw, then student i is a current winner. The best_throw is now Di, and we should add 1 to the answer.
  2. Otherwise, student i is not a current winner.
This solution has a time complexity of O(N) which is fast enough to score 100 in this problem.

Code

We can code this solution using a for loop and an if statement. Below you can see this solution written in Python and C++. I suggest trying to code the solution yourself and only look at our code after you finish or if you get stuck.

# Open the input and output files.
input_file = open("javelin.txt", "r")
output_file = open("javelout.txt", "w")

# Read the value of N and the distances from the input file.
N = int(input_file.readline().strip())
input_line = input_file.readline().strip()
D = list(map(int, input_line.split()))

# Compute the answer
answer = 0
best_throw = 0
for d in D:
    if d > best_throw:
    	# Student i is the current winner
        best_throw = d
        answer += 1

# Write the answer to the output file.
output_file.write("%d\n" % (answer))

# Finally, close the input/output files.
input_file.close()
output_file.close()
#include <cstdio>
int N;
int D[200005];
int main(void) {
    /* Open the input and output files. */
    FILE *input_file = fopen("javelin.txt", "r");
    FILE *output_file = fopen("javelout.txt", "w");

    /* Read the value of N and the distances from the input file. */
    fscanf(input_file, "%d", &N);
    for (int i = 0; i < N; i++) {
        fscanf(input_file, "%d", &D[i]);
    }

    // Compute the answer
    int best_throw = 0;
    int answer = 0;
    for (int i = 0; i < N; i++) {
        if (D[i] > best_throw) {
            // Student i is the current winner
            best_throw = D[i];
            answer++;
        }
    }

    /* Write the answer to the output file. */
    fprintf(output_file, "%d\n", answer);

    /* Finally, close the input/output files. */
    fclose(input_file);
    fclose(output_file);
}

Click here to go back.