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:
- Filtering: Select only the fruits with sweetness \(K\) or higher
- 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
-1should 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
- Read \(N\) and \(K\)
- Read the list of sweetness levels \(S\)
- Create a list
fruitscontaining only those \(S_i\) satisfying \(S_i \geq K\) - If
fruitsis empty, output-1 - If
fruitsis not empty, outputsum(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) == 0before computing the averageIn Python, the
/operator on integers automatically returns a floating-point number, so no explicit type conversion is neededAlthough \(N\) can be as large as \(10^6\), using list comprehension and
sumin Python is fast enough to handle thisSource 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: