B - 祭日の来客 / Festival Visitors: The Busiest Day Editorial by admin Editorial for printing
swe-2-highSolution
Overview
We need the earliest (smallest-indexed) day among those attaining the maximum of \(A_1, A_2, \ldots, A_N\). A simple linear scan suffices.
Algorithm
Scan the days in order \(i = 1, 2, \ldots, N\), keeping track of best (the maximum visitor count seen so far) and bestDay (the day it was achieved). Initialize best = -1 and bestDay = 1 (since \(A_i \geq 0\), day 1 always triggers an update).
For each \(i\), if \(A_i > \) best, update best to \(A_i\) and bestDay to \(i\). If equal, do nothing. After the scan, output bestDay.
Proof of correctness
Lemma: After processing day \(i\), best equals \(\max(A_1, \ldots, A_i)\) and bestDay is the smallest index achieving that maximum.
Proof (induction): For \(i = 1\): since \(A_1 \geq 0 > -1 = \) best, the update always fires, giving best = A_1, bestDay = 1. The claim holds.
Assume it holds through day \(i - 1\). On day \(i\):
- If \(A_i > \)
best: \(A_i\) is the unique maximum of days \(1\) through \(i\), so updating tobest = A_i,bestDay = iis correct. - If \(A_i \leq \)
best: the maximum over days \(1\) to \(i\) is unchanged, and the smallest index achieving it is stillbestDay(even when \(A_i = \)best,bestDay\(< i\) is earlier). Not updating is correct.
Thus at \(i = N\), bestDay is the smallest index attaining \(\max(A_1, \ldots, A_N)\), which is exactly the required answer.
Tie-breaking
When multiple days share the maximum count, the strict inequality A_i > best ensures the earliest such day is retained.
Complexity
- Time: \(O(N)\), including reading the input.
- Space: \(O(1)\) for C++ and \(O(N)\) for Python, including stored input and output arrays or strings.
posted:
last update: