Official

A - 株価の変動幅 / Stock Price Fluctuation Range Editorial by admin

GPT 5.2 High

Overview

For each stock, calculate the “sum of absolute differences between consecutive daily prices (volatility)” and find the stock number with the maximum value (if there’s a tie, choose the smallest number).

Analysis

The volatility of stock \(i\) can be calculated directly from the definition:
\(\displaystyle \sum_{j=1}^{M-1} |A_{i,j+1}-A_{i,j}|\)
In other words, for each row (stock), we simply iterate through the price sequence from left to right, accumulating the absolute differences between adjacent values.

The key point in this problem is to “choose the smallest number when the maximum values are equal.”
To achieve this, when updating the maximum volatility best_val, we only update when the value is “\(>\) (strictly greater)” and do not update when it is “\(=\) (equal).” This way, the stock that appeared first (with the smaller number) automatically remains selected.

Even in the straightforward approach, the total data is at most \(N \times M \le 10000\) entries, so computing everything is sufficiently fast. Rather, the main points for avoiding WA are “correctly summing the volatility” and “properly handling ties” when comparing all stocks.

Example: If the stock prices are [10, 13, 8], then the volatility is
\(|13-10| + |8-13| = 3 + 5 = 8\).

Algorithm

  1. Initialize with best_val = -1, best_idx = 1.
  2. For each stock \(i=1..N\), do the following:
    • Read the price sequence \(A_{i,1..M}\).
    • Set s = 0, and for \(j=1..M-1\), accumulate s += |A_{i,j+1} - A_{i,j}| to compute the volatility s.
    • If s > best_val, update best_val = s, best_idx = i.
  3. Output best_idx.
    (Since we do not update on ties, the smallest number is preserved)

Complexity

  • Time complexity: \(O(NM)\) (computing adjacent differences once for all days of all stocks)
  • Space complexity: \(O(M)\) (temporarily holding the prices for one stock)

Implementation Notes

  • To select the smallest number on ties, use > instead of >= as the update condition.

  • Make sure to take the absolute value of adjacent differences, e.g., abs(row[j + 1] - row[j]).

  • Reading input all at once with sys.stdin.read() and extracting values sequentially with an iterator allows for a concise implementation.

    Source Code

import sys

def main():
    data = sys.stdin.read().strip().split()
    if not data:
        return
    it = iter(map(int, data))
    N = next(it)
    M = next(it)

    best_idx = 1
    best_val = -1

    for i in range(1, N + 1):
        row = [next(it) for _ in range(M)]
        s = 0
        for j in range(M - 1):
            s += abs(row[j + 1] - row[j])
        if s > best_val:
            best_val = s
            best_idx = i

    print(best_idx)

if __name__ == "__main__":
    main()

This editorial was generated by gpt-5.2-high.

posted:
last update: