公式

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

DeepSeek V3

Overview

This problem asks you to calculate the volatility (the sum of absolute differences in stock prices between adjacent days) from each stock’s price data, and find the stock number with the maximum volatility.

Analysis

What the problem requires is to calculate the “volatility” for each stock by summing the absolute differences in stock prices between adjacent days, and to identify the stock with the maximum volatility. When multiple stocks have the same volatility, you must select the one with the smallest number.

Since this problem can be solved by simply calculating and comparing the volatility of each stock, no special algorithms or data structures are needed. Given the small constraints of \(N, M \leq 100\), a straightforward approach using nested loops is sufficiently fast.

Algorithm

  1. Read the number of stocks \(N\) and the number of days \(M\) from the input
  2. For each stock \(i\) \((1 \leq i \leq N)\):
    • Read the stock price data
    • Calculate the volatility \(\displaystyle\sum_{j=1}^{M-1} |A_{i,j+1} - A_{i,j}|\)
  3. Compare the calculated volatilities and record the maximum value and its stock number
  4. When volatilities are equal, prioritize the smaller stock number
  5. Output the finally selected stock number

Complexity

  • Time complexity: \(O(N \times M)\)
    • Because \(M-1\) calculations are performed for each stock
  • Space complexity: \(O(N \times M)\)
    • Because all stock price data is stored in memory

Implementation Notes

  • Use the abs() function to obtain absolute values when calculating volatility

  • Initialize the maximum value to -1 and the result index to -1

  • Don’t forget to handle the case where volatilities are equal (the elif variation == max_variation part)

  • Read input data efficiently using sys.stdin.read().splitlines()

    Source Code

def main():
    import sys
    data = sys.stdin.read().splitlines()
    n, m = map(int, data[0].split())
    max_variation = -1
    result_index = -1
    
    for i in range(1, n + 1):
        prices = list(map(int, data[i].split()))
        variation = 0
        for j in range(m - 1):
            variation += abs(prices[j + 1] - prices[j])
            
        if variation > max_variation:
            max_variation = variation
            result_index = i
        elif variation == max_variation:
            if result_index == -1 or i < result_index:
                result_index = i
                
    print(result_index)

if __name__ == "__main__":
    main()

This editorial was generated by deepseekv3.

投稿日時:
最終更新: