C - りんご狩りの最適プラン / Optimal Apple Picking Plan Editorial by admin Editorial for printing
gpt-5.3-codexOverview
For each tree, if we regard the “net profit from harvesting” as \(A_i - C\), the problem reduces to finding the “maximum sum of a contiguous subarray (where an empty interval is allowed).”
This can be solved in \(O(N)\) using Kadane’s algorithm (maximum subarray sum).
Analysis
The profit when choosing the interval \([l, r]\) is
[ \left(\sum_{i=l}^{r} A_i\right) - (r-l+1)C ]
Rearranging this gives
[ \sum_{i=l}^{r}(A_i - C) ]
In other words, if we define \(B_i = A_i - C\) for each element, we just need to find the “maximum contiguous subarray sum of \(B\).”
Naively trying all intervals would require checking \(O(N^2)\) intervals, which is too slow (\(N \le 150000\)).
Instead, we use Kadane’s algorithm to find the maximum subarray sum in linear time.
The idea behind Kadane’s algorithm:
- current = “maximum sum of a contiguous subarray ending at the current position”
- When looking at the next element \(x\):
- Extend the previous subarray: current + x
- Start a new subarray from here (effectively from 0 if empty intervals are allowed): 0
- Therefore, current = max(0, current + x)
By recording the maximum value of current in best, we obtain the answer.
Since an empty interval (selecting no trees at all) is allowed, the answer is at least 0.
As an example, when \(A=[8,3,10], C=5\),
\(B=[3,-2,5]\). The maximum contiguous sum is \(3+(-2)+5=6\), so the maximum profit is also 6.
Algorithm
- Initialize
best = 0,current = 0. - For each tree, compute
x = A_i - C. - Update
current = max(0, current + x)(discard if it becomes negative). - Update
best = max(best, current). - After processing all elements, output
best.
Complexity
- Time complexity: \(O(N)\)
- Space complexity: \(O(1)\)
Implementation Notes
Since the input can be large, using
sys.stdin.readlineis recommended for safety.By not storing an array and instead reading and updating one line at a time, memory can be saved.
The condition allowing an empty interval is naturally satisfied by
max(0, ...)and initializingbest=0.Source Code
import sys
def main():
input = sys.stdin.readline
N, C = map(int, input().split())
best = 0
current = 0
for _ in range(N):
a = int(input())
x = a - C
current = max(0, current + x)
if current > best:
best = current
print(best)
if __name__ == "__main__":
main()
This editorial was generated by gpt-5.3-codex.
posted:
last update: