Official

C - 最も売れる期間 / The Best-Selling Period Editorial by admin Editorial for printing

Qwen3-Coder-480B

Overview

Find the contiguous interval whose total sales is maximized, and output that total.

Analysis

This problem asks for the “maximum sum of a contiguous subsequence,” which is a well-known problem called the Maximum Subarray Problem.

A naive approach would be to enumerate all intervals \([L, R]\) exhaustively. However, this has \(O(N^2)\) time complexity, and since \(N\) can be up to \(2 \times 10^5\), this is not practical (it will result in TLE).

The key observation is that we can greedily choose the optimal starting position of the interval while maintaining “the best cumulative sum up to a certain point.” In other words, when focusing on day \(i\), we only need to consider which is more beneficial: adding today’s value to the current running sum, or starting a new interval from today.

By making this greedy choice, we can obtain the solution in linear time.

Algorithm

To solve this problem efficiently, we use Kadane’s Algorithm.

The flow of the algorithm is as follows:

  1. Variable current_sum: holds the sum of the current contiguous interval
  2. Variable max_sum: holds the maximum contiguous sum seen so far

For each day \(i\), do the following: - Update current_sum:

  current_sum = max(V[i], current_sum + V[i])

→ Choose the better option: continue the existing interval, or start a new one - Update max_sum:

  max_sum = max(max_sum, current_sum)

The initial values are current_sum = V[0] and max_sum = V[0].

Example

Sample input:

5
-2 1 -3 4 -1

Processing flow:

i V[i] current_sum max_sum
0 -2 -2 -2
1 1 1 1
2 -3 -2 1
3 4 4 4
4 -1 3 4

Answer: 4 (sum of interval [4, 4])

Complexity

  • Time complexity: \(O(N)\)
  • Space complexity: \(O(1)\) (since the array is reused)

Implementation Notes

  • Don’t forget to initialize with the first element of the array

  • current_sum is updated at each step and determines whether to start or continue an interval

  • max_sum is the final answer, so always keep track of the maximum value

    Source Code

def main():
    import sys
    input = sys.stdin.read
    data = input().split()
    N = int(data[0])
    V = list(map(int, data[1:]))

    max_sum = V[0]
    current_sum = V[0]

    for i in range(1, N):
        current_sum = max(V[i], current_sum + V[i])
        max_sum = max(max_sum, current_sum)

    print(max_sum)

if __name__ == "__main__":
    main()

This editorial was generated by qwen3-coder-480b.

posted:
last update: