Official

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

GPT 5.2 High

Overview

Given sales \(V_i\) over \(N\) days, find the value of the maximum sum over all contiguous subarrays \([L,R]\) (maximum subarray sum).

Analysis

If we try all possible subarray sums, there are approximately \(N^2/2\) pairs \((L,R)\). A naive solution that computes the sum of each subarray and takes the maximum runs in \(O(N^2)\), which is far too slow for \(N \le 2\times 10^5\) (TLE).

The key observation is as follows:

  • If we only know “the maximum subarray sum ending at day \(i\)”, we can update it for the next day \(i+1\).
  • Let \(cur\) be the maximum subarray sum ending at day \(i\). When we consider the next element \(x=V_{i+1}\):
    • Extend the previous subarray (\(cur + x\))
    • Start a new subarray from here (\(x\))

We simply compare which of these two options is better.

In other words, the strategy is: “if a sequence of negative values causes the running sum to worsen, discard that subarray and start fresh.” This allows us to find the maximum in a single pass.

Example: \(V = [3, -5, 4, -1, 2]\) - \(cur=3, ans=3\) - \(x=-5\): \(cur=\max(-5, 3-5=-2)=-2\), \(ans=3\) - \(x=4\): \(cur=\max(4, -2+4=2)=4\), \(ans=4\) - \(x=-1\): \(cur=\max(-1, 4-1=3)=3\), \(ans=4\) - \(x=2\): \(cur=\max(2, 3+2=5)=5\), \(ans=5\) The maximum is \(5\) (sum of the subarray \([3,5]\)).

Algorithm

This is Kadane’s Algorithm (Maximum Subarray Sum).

  • \(cur\): the maximum sum of a contiguous subarray ending at the current position
  • \(ans\): the maximum sum found so far

Initialization: - \(cur = ans = V_1\) (initializing to \(0\) is dangerous because all elements might be negative)

Update (scanning from left to right): - For the next value \(x\):
\(cur = \max(x,\; cur + x)\) - \(ans = \max(ans,\; cur)\)

Finally, output \(ans\).

Complexity

  • Time complexity: \(O(N)\) (single pass)
  • Space complexity: \(O(1)\) (only constant extra space beyond the input array)

Implementation Notes

  • To handle the case where all elements are negative correctly, initialize \(cur\) and \(ans\) with the first element \(V_1\) (if initialized to \(0\), the answer might incorrectly become \(0\)).

  • Since the input size can be large, fast input methods such as sys.stdin.buffer.read() are effective in Python.

    Source Code

import sys

def main():
    data = list(map(int, sys.stdin.buffer.read().split()))
    n = data[0]
    v = data[1:1+n]

    cur = ans = v[0]
    for x in v[1:]:
        cur = max(x, cur + x)
        if cur > ans:
            ans = cur

    print(ans)

if __name__ == "__main__":
    main()

This editorial was generated by gpt-5.2-high.

posted:
last update: