DOJ logoDOJ
Problems
Recently added problemsSaved problemsWorkbooks
CategoriesDLCContestsGroupsTeamsBoard
Ranking
Solved Problem RankingStreak rankingDOJ Power ranking
Status
Call for TasksLoginRegister
DOJ logoDOJ

Community online judge with OI-style subtask scoring, Elo ratings, and Discord account linking.

Problems
ProblemsCategories
Community
ContestsRankingBoardNoticesHost an external contestGuide
Account
LoginRegisterJudge Status
Policy
Terms of ServiceDLC RulesPrivacyAPI documentationLanguage runtimesContest rank rewardsRating and performance
© 2026 DOJ
All rights reserved
Editorial

Maximum Subarray Problem

Back to problem

Editorial

For subtask 111, compute the sum of every interval (l,r)(l,r)(l,r) from scratch in O(N3)O(N^3)O(N3) time.

For subtask 222, compute prefix sums Pi=A1+⋯+AiP_i=A_1+\cdots+A_iPi​=A1​+⋯+. Each interval sum is , giving time.

For the full problem, let DiD_iDi​ be the maximum sum of a nonempty subarray ending at iii. We can either take only the last element or append AiA_iAi​ to the best subarray ending at i−1i-1. Hence

D1=A1,Di=max⁡(Ai,Di−1+Ai)(2≤i≤N).D_1=A_1,\qquad D_i=\max(A_i,D_{i-1}+A_i)\quad(2\leq i\leq N).D1​=A1​,

The answer is the maximum of all DiD_iDi​. Initialize with A1A_1A1​ rather than 000 to handle arrays containing only negative values. A sum can exceed the range of a 3232-bit integer, so use a -bit integer.

The full solution uses O(N)O(N)O(N) time and O(1)O(1)O(1) extra space.

Solution written by GPT6

Ai​
Pr−Pl−1P_r-P_{l-1}Pr​−Pl−1​
O(N2)O(N^2)O(N2)
i−1
D
i​
=
max(Ai​,Di−1​+
Ai​)(2≤
i≤
N).
32
646464