Official
B - 相場の値動き / Market Price Movements Editorial by admin Editorial for printing
swe-2-highSolution
For each day \(i\) (\(2 \leq i \leq N\)), compare \(A_i\) with \(A_{i-1}\): if \(A_i > A_{i-1}\) it is an “up” day, if \(A_i < A_{i-1}\) it is a “down” day, and if \(A_i = A_{i-1}\) it is a “flat” day. Count each case.
There is no need to store the whole array; remembering only the previous day’s price suffices. While reading the input, compare the previous price prev with the current price cur, update the three counters, and then set prev to cur.
Proof of correctness
- Exhaustiveness: The relationship between \(A_i\) and \(A_{i-1}\) is exactly one of \(A_i > A_{i-1}\), \(A_i < A_{i-1}\), or \(A_i = A_{i-1}\). These cases are mutually exclusive and cover all possibilities, so each day is counted by exactly one counter.
- Correspondence: By the problem’s definition, up days, down days, and flat days correspond one-to-one with these three conditions.
- Invariant: At the start of each loop iteration,
prevholds the price of the immediately preceding day (initially \(A_1\), and updated tocurat the end of each iteration). Hence every iteration performs the correct comparison.
Therefore, when the loop finishes, the three counters equal the numbers of up, down, and flat days respectively.
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: