Official

A - 果物の選別 / Fruit Sorting Editorial by admin

Claude 4.6 Opus (Thinking)

Overview

Given \(N\) fruits, select only those with a sweetness level of \(K\) or higher, and compute the average sweetness of the selected fruits. If no fruits qualify, output -1.

Analysis

The two operations needed for this problem are:

  1. Filtering: Select only the fruits with sweetness \(K\) or higher
  2. Computing the average: Divide the total sweetness of the selected fruits by their count

For example, consider the case where \(N = 5\), \(K = 10\), and the sweetness levels are \([8, 12, 5, 15, 10]\).

  • Fruits with sweetness \(K = 10\) or higher: \(12, 15, 10\) — 3 fruits
  • Average: \((12 + 15 + 10) / 3 = 37 / 3 \approx 12.333...\)

No particularly difficult algorithm is needed — the problem can be solved by scanning all fruits once. A straightforward approach directly yields the optimal solution.

The two points to be careful about are:

  • When there are 0 eligible fruits: Division by zero is not possible, so this case must be checked first and -1 should be output
  • Precision: The total sweetness can be as large as \(10^9 \times 10^6 = 10^{15}\), but since Python integers support arbitrary precision, there is no worry about overflow. Floating-point division also provides sufficient precision

Algorithm

  1. Read \(N\) and \(K\)
  2. Read the list of sweetness levels \(S\)
  3. Create a list fruits containing only those \(S_i\) satisfying \(S_i \geq K\)
  4. If fruits is empty, output -1
  5. If fruits is not empty, output sum(fruits) / len(fruits)

Complexity

  • Time complexity: \(O(N)\) — Scan all fruits once for filtering, and compute the sum and count
  • Space complexity: \(O(N)\) — Storing the input and the list of qualifying fruits (at most \(N\) items)

Implementation Notes

  • List comprehension provides a concise way to filter: [s for s in S if s >= K]

  • Avoiding division by zero: Check len(fruits) == 0 before computing the average

  • In Python, the / operator on integers automatically returns a floating-point number, so no explicit type conversion is needed

  • Although \(N\) can be as large as \(10^6\), using list comprehension and sum in Python is fast enough to handle this

    Source Code

N, K = map(int, input().split())
S = list(map(int, input().split()))

fruits = [s for s in S if s >= K]

if len(fruits) == 0:
    print(-1)
else:
    print(sum(fruits) / len(fruits))

This editorial was generated by claude4.6opus-thinking.

posted:
last update: