{"id":"maximum-subarray","title":"Maximum Subarray","difficulty":"medium","patterns":["dp-1d"],"primaryConcept":"dp-1d-decision","concepts":["dp-1d-decision"],"problemForm":"core","companies":[],"category":"dynamic-programming","compareMode":"exact","syntheticTestConfig":{"inputShape":"array","primaryParam":"nums","sizeMetric":"length"},"description":"Given an integer array, find the largest possible sum of a non-empty contiguous subarray.","examples":[{"input":"nums = [-2,1,-3,4,-1,2,1,-5,4]","output":"6","explanation":"The subarray [4,-1,2,1] has the largest sum."},{"input":"nums = [1]","output":"1","explanation":"The only element is the best non-empty subarray."},{"input":"nums = [-3,-2,-5]","output":"-2","explanation":"For all-negative input, choose the least negative single element."}],"constraints":[{"id":"1-len-nums-10-5","text":"1 <= len(nums) <= 10^5","check":{"kind":"sizeRange","target":"nums","measure":"arrayLength","min":1,"max":100000}},{"id":"10-4-nums-i-10-4","text":"-10^4 <= nums[i] <= 10^4","check":{"kind":"valueRange","target":"nums","selector":"arrayItems","min":-10000,"max":10000}},{"id":"the-subarray-must-contain-at-least-one-element","text":"The subarray must contain at least one element"}],"starterCode":"class Solution:\n    def maxSubArray(self, nums: list[int]) -> int:\n        # Your code here\n        pass","functionName":"maxSubArray","testCases":[{"id":"1","input":{"nums":[-2,1,-3,4,-1,2,1,-5,4]},"expected":6,"description":"Canonical mixed input."},{"id":"2","input":{"nums":[1]},"expected":1,"description":"Single element."},{"id":"3","input":{"nums":[5,4,-1,7,8]},"expected":23,"description":"Best subarray is the whole array."},{"id":"4","input":{"nums":[-3,-2,-5]},"expected":-2,"description":"All negative values."},{"id":"5","input":{"nums":[-1,0,-2]},"expected":0,"description":"Zero can be the best non-empty subarray."},{"id":"h1","input":{"nums":[-3,-1,-2]},"description":"All-negative input picks the least-bad element.","expected":-1},{"id":"h2","input":{"nums":[5,-2,3,-1,2]},"description":"A mid-array run beats any single element.","expected":7},{"id":"h3","input":{"nums":[1,-3,2,1,-1]},"description":"The best subarray starts after an early dip.","expected":3},{"id":"h4","input":{"nums":[0,-1,0,-2,0]},"description":"Zeros keep the maximum at zero.","expected":0},{"id":"h5","input":{"nums":[4,-1,2,1,-5,4]},"description":"A classic mixed sequence with a strong prefix run.","expected":6},{"id":"later-singleton-beats-prefix","input":{"nums":[100,-101,102]},"description":"A later singleton can beat a tempting large prefix after a deep drop.","expected":102},{"id":"middle-run-before-tail-recovery","input":{"nums":[-2,3,-1,3,-5,4]},"description":"The best middle run should not be extended through a harmful tail gap.","expected":5}],"hints":[{"level":1,"content":"At each index, decide whether to extend the previous subarray or start fresh at the current value.","revealPattern":false},{"level":2,"content":"Track both the best subarray ending here and the best sum seen anywhere.","revealPattern":true},{"level":3,"content":"Initialize from `nums[0]`, not zero, so all-negative arrays work correctly.","revealPattern":true}],"guidedFlow":{"approachSelection":{"contract":"approach-selection-v1","question":"Which approach should we implement?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"all-subarrays","name":"Check every subarray","summary":"Try every start and end position and compute the sum for each candidate.","decisionReason":"Re-totalling every start costs on the order of n squared additions, which at 100,000 numbers runs into the billions.","complexity":{"time":"O(n^2)","space":"O(1)"},"tradeoffs":["Runs in O(n^2) time and uses O(1) space."],"isOptimal":false},{"id":"ending-index-dp","name":"One pass over the positions","summary":"Sweep the list once, keeping one value per position and a single overall best.","decisionReason":"Every number is read once and nothing is re-added, so 100,000 numbers cost 100,000 steps.","complexity":{"time":"O(n)","space":"O(n)"},"tradeoffs":["Runs in O(n) time and uses O(n) space."],"isOptimal":true}]},"codingCheckpoints":[{"id":"init-first","title":"Seed the first DP value","description":"Create the dp array and set dp[0] to nums[0] before the scan begins.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"writes_input_indexed_base_case","scope":"set-base-case","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Seed an indexed DP state with its base case before recurrence scanning.","doneWhen":"The indexed DP store exists and its base position is written before the loop.","shouldFailWhen":"The code scans transitions without seeding the first DP state.","roles":["indexed DP state","base case"],"mustProve":["indexed state initialization","indexed base-case write from the first input value"],"mustNotAccept":["unseeded recurrence state","constant or unrelated-source base write"],"proofSnippets":[{"id":"py-init-first","language":"python","code":"def maxSubArray(nums):\n    dp = [0] * len(nums)\n    dp[0] = nums[0]"}]},"commonMistakes":["Leaving dp[0] at 0","Seeding dp[0] from 0 and breaking all-negative lists"],"hint":"The only run ending at index 0 holds exactly nums[0]."},{"id":"extend-or-restart","title":"Choose extend or restart","description":"For each later index, set dp[i] to the larger of nums[i] alone and dp[i - 1] + nums[i].","validation":{"type":"semantic","validator":"all","params":[{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"computes_recurrence_transition","scope":"compute-next-states","readMode":"dp-value-query-v1"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"writes_recurrence_state","scope":"keep-better-outcome","readMode":"dp-value-query-v1"}]}]},"semanticSpec":{"intent":"Compute and write each indexed recurrence transition.","doneWhen":"The loop writes a DP transition for each later index using prior DP state and current input.","shouldFailWhen":"The loop scans indices but never writes the recurrence result back to DP state.","roles":["scan index","indexed DP state","input value"],"mustProve":["recurrence transition computation","recurrence state writeback"],"mustNotAccept":["scan without DP write"],"proofSnippets":[{"id":"py-extend-or-restart","language":"python","code":"def maxSubArray(nums):\n    dp = [0] * len(nums)\n    dp[0] = nums[0]\n    for i in range(1, len(nums)):\n        dp[i] = max(nums[i], dp[i - 1] + nums[i])"}]},"commonMistakes":["Extending even when dp[i - 1] is negative","Dropping nums[i] when the run restarts"],"hint":"A run ending at index i either starts there or reaches back through index i - 1."},{"id":"track-best","title":"Update the global best","description":"After writing dp[i], raise best if dp[i] is larger.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"updates_numeric_extremum_state","scope":"track-best","readMode":"numeric-state-value-query-v1"}]},"semanticSpec":{"intent":"Maintain a numeric extremum while scanning recurrence states.","doneWhen":"A numeric best state is updated with an extremum operation inside the recurrence scan.","shouldFailWhen":"The recurrence computes local states but never updates a global best.","roles":["numeric best state","current recurrence state"],"mustProve":["numeric extremum update"],"mustNotAccept":["returning only the final local state"],"proofSnippets":[{"id":"py-track-best","language":"python","code":"def maxSubArray(nums):\n    dp = [0] * len(nums)\n    dp[0] = nums[0]\n    best = nums[0]\n    for i in range(1, len(nums)):\n        dp[i] = max(nums[i], dp[i - 1] + nums[i])\n        best = max(best, dp[i])"}]},"commonMistakes":["Returning the last dp value instead of best","Comparing best before dp[i] is written"],"hint":"The best run may end before the final index."},{"id":"return-best","title":"Return the best sum","description":"Return best once the sweep is done.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"returns_terminal_numeric_state","readMode":"numeric-state-value-query-v1"}]},"semanticSpec":{"intent":"Return the terminal numeric answer state.","doneWhen":"The function returns the tracked numeric best after scanning.","shouldFailWhen":"The function returns the DP array, subarray values, or a stale local state.","roles":["terminal numeric result"],"mustProve":["terminal numeric state return"],"mustNotAccept":["returning a collection instead of a number"],"proofSnippets":[{"id":"py-return-best","language":"python","code":"def maxSubArray(nums):\n    dp = [0] * len(nums)\n    dp[0] = nums[0]\n    best = nums[0]\n    for i in range(1, len(nums)):\n        dp[i] = max(nums[i], dp[i - 1] + nums[i])\n        best = max(best, dp[i])\n    return best"}]},"commonMistakes":["Returning the last dp value","Returning the run's numbers instead of their sum"],"hint":"The answer is the number sitting in best."}],"version":2,"slides":[{"id":"read-the-signal","chapter":"The numbers","kind":"info","eyebrow":"Read the problem","title":"The strongest run of numbers","workspacePanel":"problem","body":["You get a list of numbers, some negative. A run is any block of neighbors, with no gaps. The job is to find the run with the largest total and report that total.","A run must hold at least one number, so the answer can be negative when every number is. That is what stops you from just skipping the negatives."]},{"id":"brute-force","chapter":"The obvious way","kind":"code-trace","eyebrow":"Try it the plain way","title":"Add up every run","summary":"The trace below does find the best run. Count how many separate totals index 4 gets added into.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"best = nums[0]\nfor i in range(len(nums)):\n    total = 0\n    for j in range(i, len(nums)):\n        total += nums[j]\n        best = max(best, total)\nreturn best","steps":[{"id":"from-zero","title":"Every run starting at 0","codeLine":5,"summary":"With the start fixed at index 0, the total runs -2, then -1, then -4 as the scan reaches index 2.","state":{"nums":[-2,1,-3,4,-1,2,1,-5,4],"i":0,"j":3}},{"id":"from-one","title":"Start over at index 1","codeLine":4,"summary":"The start moves to index 1 and total resets to 0, so the walk rightward begins again from there.","state":{"nums":[-2,1,-3,4,-1,2,1,-5,4],"i":1,"j":4}},{"id":"rewalks","title":"Another pass over the middle","codeLine":5,"summary":"The start is at index 3 and the walk has reached index 6. Every start so far has passed through index 4 on its way right.","state":{"nums":[-2,1,-3,4,-1,2,1,-5,4],"i":3,"j":6}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"let best = nums[0];\nfor (let i = 0; i < nums.length; i++) {\n    let total = 0;\n    for (let j = i; j < nums.length; j++) {\n        total += nums[j];\n        best = Math.max(best, total);\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":9},"statementBundles":{"6":{"startLine":6,"endLine":8}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"let best = nums[0];\nfor (let i = 0; i < nums.length; i++) {\n    let total = 0;\n    for (let j = i; j < nums.length; j++) {\n        total += nums[j];\n        best = Math.max(best, total);\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":9},"statementBundles":{"6":{"startLine":6,"endLine":8}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int best = nums.get(0);\nfor (int i = 0; i < nums.size(); i++) {\n    int total = 0;\n    for (int j = i; j < nums.size(); j++) {\n        total += nums.get(j);\n        best = Math.max(best, total);\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":9},"statementBundles":{"6":{"startLine":6,"endLine":8}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int best = nums[0];\nfor (int i = 0; i < nums.Count; i++) {\n    int total = 0;\n    for (int j = i; j < nums.Count; j++) {\n        total += nums[j];\n        best = Math.Max(best, total);\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":9},"statementBundles":{"6":{"startLine":6,"endLine":8}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"int best = nums[0];\nfor (int i = 0; i < nums.size(); i++) {\n    int total = 0;\n    for (int j = i; j < nums.size(); j++) {\n        total += nums[j];\n        best = max(best, total);\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":9},"statementBundles":{"6":{"startLine":6,"endLine":8}}}}},"body":["An outer loop fixes the start of the run; an inner loop grows it rightward, adding one number at a time."]},{"id":"repeated-work","chapter":"The obvious way","kind":"case-probe","eyebrow":"Count the cost","title":"How much work does the nested scan do on a list of n numbers?","workspacePanel":"trace","options":[{"id":"n-squared","label":"On the order of n squared additions","rationale":"The start at index 0 sums up to n numbers, the start at index 1 sums n - 1, and so on down to 1. That total grows like n squared: at 100,000 numbers it is about five billion additions.","isCorrect":true},{"id":"linear","label":"About n additions, one per number","rationale":"One addition per number would mean each number is added into exactly one total. Here the start at index 1 adds the same numbers the start at index 0 already added.","isCorrect":false},{"id":"n-log-n","label":"About n log n, like a sort","rationale":"Nothing here halves the work each round. Every start walks all the way to the end, so each of the n starts does linear work rather than logarithmic.","isCorrect":false}],"answer":"On the order of n squared. Each of the n starts walks to the end of the list, re-adding the same stretch every time the start moves over.","summary":"The list in the trace held nine numbers. The constraints allow 100,000."},{"id":"approach-selection","chapter":"The idea","kind":"choice","source":"approach-selection","eyebrow":"Pick the approach","title":"Which shape should we build?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-selection-state","state":{"nums":[-2,1,-3,4,-1,2,1,-5,4],"i":0}}]}},{"id":"running-value","kind":"info","chapter":"The idea","eyebrow":"Name the value","title":"Keep one value per position","workspacePanel":"visualizer","body":["The nested scan threw its running total away every time the start moved and rebuilt it from the new start. One sweep can keep a value at each position instead, computed as the sweep arrives there.","Those values live in an array called dp, so dp[i] belongs to index i, and cur names the one at the position being read right now. The open question is what single number index i should keep so that no run is lost."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"running-value-state","state":{"nums":[-2,1,-3,4,-1,2,1,-5,4],"i":3,"cur":-2}}]}},{"id":"state-meaning","chapter":"The idea","kind":"case-probe","eyebrow":"Define the state","title":"What does dp[3] hold when the sweep reaches index 3?","summary":"The sweep has just arrived at index 3.","workspacePanel":"visualizer","options":[{"id":"ending-here","label":"The best non-empty sum ending exactly at this index","rationale":"Every run ends at some index, so one value per ending index covers every run without listing any of them. dp[3] is the largest sum among the runs that stop at index 3.","isCorrect":true},{"id":"best-anywhere","label":"The best sum found anywhere in the array","rationale":"The best run anywhere may end well before index 3, so a value reporting it says nothing about the runs that stop at index 3.","isCorrect":false},{"id":"prefix-total","label":"The sum of every number read so far","rationale":"A prefix total keeps every earlier number, including negatives that a run ending at index 3 is free to leave out.","isCorrect":false}],"answer":"dp[i] holds the largest sum among the non-empty runs that end exactly at index i.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state-meaning-state","state":{"nums":[-2,1,-3,4,-1,2,1,-5,4],"i":3,"cur":-2}}]}},{"id":"negative-prefix","chapter":"The idea","kind":"case-probe","eyebrow":"Check the choice","title":"What can dp[2] do for the 4 at index 3?","summary":"dp[2] is -2, and nums[3] is 4.","workspacePanel":"visualizer","options":[{"id":"smaller","label":"Only make the run ending at index 3 smaller","rationale":"-2 + 4 = 2, below the 4 on its own, so carrying that run into index 3 costs 2 of the 4.","isCorrect":true},{"id":"larger","label":"Guarantee a larger run ending at index 3","rationale":"Adding -2 lowers whatever sum it joins, so no run ending at index 3 grows by including it.","isCorrect":false},{"id":"unchanged","label":"Leave the sum at index 3 unchanged","rationale":"Joining the earlier run changes the candidate from 4 to -2 + 4 = 2.","isCorrect":false}],"answer":"-2 + 4 = 2, below the 4 on its own, so carrying the earlier run into index 3 costs 2 of the 4.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"negative-prefix-state","state":{"nums":[-2,1,-3,4,-1,2,1,-5,4],"i":3,"cur":-2}}]}},{"id":"extend-or-restart","chapter":"The idea","kind":"case-probe","eyebrow":"Find the choice","title":"For the best run ending at a number, what are the only two options?","workspacePanel":"visualizer","options":[{"id":"extend-or-start","label":"Extend the best run ending just before it, or start fresh at this number","rationale":"A run ending at index i either holds nums[i] alone or reaches back through index i - 1, and the best it can do back there is dp[i - 1].","isCorrect":true},{"id":"global-best-plus","label":"Add this number to the best run found anywhere so far","rationale":"The best run anywhere might end far to the left, with a gap before this number. A run has no gaps, so only the run ending at index i - 1 can be extended.","isCorrect":false},{"id":"always-extend","label":"Always extend the previous run","rationale":"When dp[i - 1] is negative, extending drags nums[i] below its own value, and the run holding nums[i] alone beats it.","isCorrect":false}],"answer":"dp[i] = max(nums[i], dp[i - 1] + nums[i]). Either the run starts at index i, or it runs through index i - 1, where dp[i - 1] is already the best it could be.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"extend-or-restart-state","state":{"nums":[-2,1,-3,4,-1,2,1,-5,4],"i":3,"cur":-2}}]}},{"id":"track-best","chapter":"The idea","kind":"case-probe","eyebrow":"Find the answer","title":"The sweep fills dp[i] at every index. Where is the final answer?","workspacePanel":"visualizer","options":[{"id":"max-of-all","label":"The largest dp value anywhere in the array","rationale":"Every run ends somewhere, so every run is counted by exactly one dp value. The largest of those values is the largest run sum.","isCorrect":true},{"id":"last-value","label":"The dp value at the last index","rationale":"dp at the last index only covers runs that end at the final number. Later negatives can keep it low long after the best run has finished.","isCorrect":false},{"id":"sum-all","label":"The total of every dp value","rationale":"Different dp entries describe overlapping runs, so adding them counts the same numbers many times over. The answer is one run's sum.","isCorrect":false}],"answer":"The largest dp value seen anywhere. The best run can end in the middle, so a separate maximum has to keep the high point as the sweep moves past it.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"track-best-state","state":{"nums":[-2,1,-3,4,-1,2,1,-5,4],"i":6,"cur":6,"best":6}}]}},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"One value per index, one best","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"dry-run-start","state":{"nums":[-2,1,-3,4,-1,2,1,-5,4],"i":0,"cur":-2,"best":-2}}]},"body":["The only run ending at index 0 is nums[0] on its own, so dp[0] and best both start there.","Each later step sets dp[i] = max(nums[i], dp[i - 1] + nums[i]), then raises best if dp[i] is larger. The panel shows the latest dp value as cur."]},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the run","title":"Trace the running best","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup","state":{"nums":[-2,1,-3,4,-1,2,1,-5,4],"i":0,"cur":-2,"best":-2}},{"id":"restart-one","state":{"nums":[-2,1,-3,4,-1,2,1,-5,4],"i":1,"cur":1,"best":1}},{"id":"restart-four","state":{"nums":[-2,1,-3,4,-1,2,1,-5,4],"i":3,"cur":4,"best":4}},{"id":"peak","state":{"nums":[-2,1,-3,4,-1,2,1,-5,4],"i":6,"cur":6,"best":6}}]},"beats":[{"id":"restart-one","title":"cur is -2 going into index 1. Extend or restart?","prompt":"The current number is 1.","options":[{"id":"restart","label":"Restart: cur becomes 1","rationale":"max(1, -2 + 1) = 1, so cur becomes 1. Carrying the -2 forward would leave the run at -1.","isCorrect":true},{"id":"extend","label":"Extend: cur becomes -1","rationale":"-2 + 1 = -1, which is the smaller of the two candidates for a run ending at index 1.","isCorrect":false},{"id":"keep","label":"Keep cur at -2","rationale":"cur belongs to the index being read. At index 1 it has to describe runs ending at index 1, and the best of those is 1.","isCorrect":false}],"answer":"Restart. cur = max(1, -2 + 1) = 1, and best rises from -2 to 1."},{"id":"restart-four","title":"Index 2 left cur at -2. What is cur at index 3?","prompt":"The current number is 4.","options":[{"id":"four","label":"4, by restarting","rationale":"max(4, -2 + 4) = 4, so cur restarts at 4 and best climbs from 1 to 4.","isCorrect":true},{"id":"two","label":"2, by extending","rationale":"-2 + 4 = 2 is a real run ending at index 3, just not the best one. The 4 on its own beats it.","isCorrect":false},{"id":"six","label":"6, adding to the best so far","rationale":"6 would be the 1 at index 1 plus the 4 at index 3, and no run can jump over the -3 sitting between them.","isCorrect":false}],"answer":"4. cur = max(4, -2 + 4) = 4, and best becomes 4."},{"id":"peak","title":"cur reaches 6 at index 6, and best rises with it","prompt":"The numbers left are -5 at index 7 and 4 at index 8. What does best hold when the sweep ends?","options":[{"id":"six","label":"6, the peak from index 6","rationale":"cur drops to max(-5, 6 - 5) = 1 at index 7, then max(4, 1 + 4) = 5 at index 8. Neither beats 6.","isCorrect":true},{"id":"stays-four","label":"5, cur's value at the last index","rationale":"cur does end at 5, but best only ever moves up, and it recorded 6 two indices earlier.","isCorrect":false},{"id":"later","label":"10, the 6 plus the final 4","rationale":"Joining those two would have to include the -5 at index 7, giving 6 - 5 + 4 = 5. Nothing may be skipped.","isCorrect":false}],"answer":"6. cur falls to 1 and comes back to 5, so best keeps the 6 it recorded at index 6."}]},{"id":"zero-init-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Should best start at 0?","summary":"Starting best at 0 looks like a neutral floor, and on any list holding a positive run it returns the right answer. The trace below feeds it [-3, -1, -2].","workspacePanel":"trace","pitfall":"The code below starts best at 0 before the scan.","whyItMatters":"A best of 0 stands for a run holding nothing, which the problem forbids. Seed best and cur from nums[0] so the answer stays on runs that exist.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"best = 0\ncur = 0\nfor num in nums:\n    cur = max(num, cur + num)\n    best = max(best, cur)\nreturn best","steps":[{"id":"first-neg","title":"best holds at 0","codeLine":5,"summary":"nums = [-3, -1, -2]. The first number is -3, so cur is -3, but best stays at its starting 0.","state":{"nums":[-3,-1,-2],"i":0,"cur":-3,"best":0}},{"id":"all-neg","title":"Every cur is negative","codeLine":4,"summary":"Each number is negative, so cur is always below 0 and best never rises above its starting value.","state":{"nums":[-3,-1,-2],"i":1,"cur":-1,"best":0}},{"id":"wrong-zero","title":"It returns 0","codeLine":6,"summary":"No run sums to 0 here, and a run must hold a number. The real answer is -1, the least-negative value.","state":{"nums":[-3,-1,-2],"i":2,"cur":-2,"best":0}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"let best = 0;\nlet cur = 0;\nfor (const num of nums) {\n    cur = Math.max(num, (cur + num));\n    best = Math.max(best, cur);\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7},"statementBundles":{"5":{"startLine":5,"endLine":6}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"let best = 0;\nlet cur = 0;\nfor (const num of nums) {\n    cur = Math.max(num, (cur + num));\n    best = Math.max(best, cur);\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7},"statementBundles":{"5":{"startLine":5,"endLine":6}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int best = 0;\nint cur = 0;\nfor (Integer num : nums) {\n    cur = Math.max(num, (cur + num));\n    best = Math.max(best, cur);\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7},"statementBundles":{"5":{"startLine":5,"endLine":6}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int best = 0;\nint cur = 0;\nforeach (int num in nums) {\n    cur = Math.Max(num, cur + num);\n    best = Math.Max(best, cur);\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7},"statementBundles":{"5":{"startLine":5,"endLine":6}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"int best = 0;\nint cur = 0;\nfor (int num : nums) {\n    cur = max(num, (cur + num));\n    best = max(best, cur);\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7},"statementBundles":{"5":{"startLine":5,"endLine":6}}}}}},{"id":"edge-case-intro","kind":"info","chapter":"Edge cases","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","body":["The sweep keeps dp[i] for the run ending at each index and best for the largest of those values.","Two inputs to try against it: [4, -1, 2, 1, -5], where the last number is negative, and a list holding a single number."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"intro-state","state":{"nums":[-2,1,-3,4,-1,2,1,-5,4],"i":0,"cur":-2,"best":-2}}]}},{"id":"all-negative-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"What does the sweep return on [4, -1, 2, 1, -5]?","summary":"The sweep has just read the final -5.","workspacePanel":"visualizer","options":[{"id":"best-holds-six","label":"6, the peak from earlier in the sweep","rationale":"The run 4, -1, 2, 1 ends at index 3 and sums to 6. best recorded it there, and the -5 that follows cannot lower it.","isCorrect":true},{"id":"final-cur","label":"1, the running value after the last number","rationale":"cur is 1 because the -5 dragged it down. cur only describes runs that end at index 4, and the best run ends at index 3.","isCorrect":false},{"id":"whole-sum","label":"7, the positive numbers 4, 2 and 1","rationale":"Those three are not neighbors; taking them means skipping the -1 at index 1. Paying that -1 to join them gives 6.","isCorrect":false}],"answer":"6. best held the peak from index 3, and the trailing -5 only moved cur.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"best-before-end-state","state":{"nums":[4,-1,2,1,-5],"i":4,"cur":1,"best":6}}]}},{"id":"single-number-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"What if the list holds a single number?","summary":"nums = [-4], a list of one.","workspacePanel":"visualizer","options":[{"id":"the-number","label":"-4, the number itself","rationale":"dp[0] and best both start at -4, and there is no index 1 for the sweep to visit.","isCorrect":true},{"id":"zero","label":"0, since it is negative","rationale":"A run must hold at least one number, and the only run here is -4. 0 would report an empty run.","isCorrect":false},{"id":"error","label":"There is no valid run","rationale":"A single number is a valid run of length one. Its sum is that number.","isCorrect":false}],"answer":"-4. dp[0] and best both begin at the only number and stay there.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"single-number-edge-state","state":{"nums":[-4],"i":0,"cur":-4,"best":-4}}]}},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Turn the rule into code","summary":"The run restarts the moment carrying the previous one forward would only cost the next number.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-to-code-start","state":{"nums":[-2,1,-3,4,-1,2,1,-5,4],"i":0,"cur":-2,"best":-2}}]},"body":["Fill dp left to right: dp[0] is nums[0], and dp[i] is max(nums[i], dp[i - 1] + nums[i]).","Keep best beside it, seeded from nums[0] and raised whenever dp[i] passes it, and return best once the sweep is done."]},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the one-pass sweep","eyebrow":"Code the rule","summary":"Seed dp[0] from nums[0], fill each later dp[i] from nums[i] and dp[i - 1], raise best as you go, and return best.","workspacePanel":"code","checkpoints":[{"id":"init-first","title":"Seed the first DP value","description":"Create the dp array and set dp[0] to nums[0] before the scan begins.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"writes_input_indexed_base_case","scope":"set-base-case","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Seed an indexed DP state with its base case before recurrence scanning.","doneWhen":"The indexed DP store exists and its base position is written before the loop.","shouldFailWhen":"The code scans transitions without seeding the first DP state.","roles":["indexed DP state","base case"],"mustProve":["indexed state initialization","indexed base-case write from the first input value"],"mustNotAccept":["unseeded recurrence state","constant or unrelated-source base write"],"proofSnippets":[{"id":"py-init-first","language":"python","code":"def maxSubArray(nums):\n    dp = [0] * len(nums)\n    dp[0] = nums[0]"}]},"commonMistakes":["Leaving dp[0] at 0","Seeding dp[0] from 0 and breaking all-negative lists"],"hint":"The only run ending at index 0 holds exactly nums[0]."},{"id":"extend-or-restart","title":"Choose extend or restart","description":"For each later index, set dp[i] to the larger of nums[i] alone and dp[i - 1] + nums[i].","validation":{"type":"semantic","validator":"all","params":[{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"computes_recurrence_transition","scope":"compute-next-states","readMode":"dp-value-query-v1"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"writes_recurrence_state","scope":"keep-better-outcome","readMode":"dp-value-query-v1"}]}]},"semanticSpec":{"intent":"Compute and write each indexed recurrence transition.","doneWhen":"The loop writes a DP transition for each later index using prior DP state and current input.","shouldFailWhen":"The loop scans indices but never writes the recurrence result back to DP state.","roles":["scan index","indexed DP state","input value"],"mustProve":["recurrence transition computation","recurrence state writeback"],"mustNotAccept":["scan without DP write"],"proofSnippets":[{"id":"py-extend-or-restart","language":"python","code":"def maxSubArray(nums):\n    dp = [0] * len(nums)\n    dp[0] = nums[0]\n    for i in range(1, len(nums)):\n        dp[i] = max(nums[i], dp[i - 1] + nums[i])"}]},"commonMistakes":["Extending even when dp[i - 1] is negative","Dropping nums[i] when the run restarts"],"hint":"A run ending at index i either starts there or reaches back through index i - 1."},{"id":"track-best","title":"Update the global best","description":"After writing dp[i], raise best if dp[i] is larger.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"updates_numeric_extremum_state","scope":"track-best","readMode":"numeric-state-value-query-v1"}]},"semanticSpec":{"intent":"Maintain a numeric extremum while scanning recurrence states.","doneWhen":"A numeric best state is updated with an extremum operation inside the recurrence scan.","shouldFailWhen":"The recurrence computes local states but never updates a global best.","roles":["numeric best state","current recurrence state"],"mustProve":["numeric extremum update"],"mustNotAccept":["returning only the final local state"],"proofSnippets":[{"id":"py-track-best","language":"python","code":"def maxSubArray(nums):\n    dp = [0] * len(nums)\n    dp[0] = nums[0]\n    best = nums[0]\n    for i in range(1, len(nums)):\n        dp[i] = max(nums[i], dp[i - 1] + nums[i])\n        best = max(best, dp[i])"}]},"commonMistakes":["Returning the last dp value instead of best","Comparing best before dp[i] is written"],"hint":"The best run may end before the final index."},{"id":"return-best","title":"Return the best sum","description":"Return best once the sweep is done.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"returns_terminal_numeric_state","readMode":"numeric-state-value-query-v1"}]},"semanticSpec":{"intent":"Return the terminal numeric answer state.","doneWhen":"The function returns the tracked numeric best after scanning.","shouldFailWhen":"The function returns the DP array, subarray values, or a stale local state.","roles":["terminal numeric result"],"mustProve":["terminal numeric state return"],"mustNotAccept":["returning a collection instead of a number"],"proofSnippets":[{"id":"py-return-best","language":"python","code":"def maxSubArray(nums):\n    dp = [0] * len(nums)\n    dp[0] = nums[0]\n    best = nums[0]\n    for i in range(1, len(nums)):\n        dp[i] = max(nums[i], dp[i - 1] + nums[i])\n        best = max(best, dp[i])\n    return best"}]},"commonMistakes":["Returning the last dp value","Returning the run's numbers instead of their sum"],"hint":"The answer is the number sitting in best."}]},{"id":"complete","kind":"complete","chapter":"Code","title":"What to carry forward","eyebrow":"Take it with you","summary":"dp[i] is the best run ending at index i, and best is the largest dp value the sweep has seen.","workspacePanel":"code","body":["The best run ending at index i is either nums[i] on its own or nums[i] on top of dp[i - 1].","best keeps the largest of those values, since the strongest run can end anywhere in the list."],"takeaways":[{"title":"Extend or restart, nothing else","body":"dp[i] = max(nums[i], dp[i - 1] + nums[i]) is the whole decision, and a negative dp[i - 1] is always worth dropping."},{"title":"The peak can be in the middle","body":"best keeps the largest dp value ever written, so a strong early run survives the negatives that follow it."},{"title":"Every run ends at one index","body":"Filling one value per index covers all of them in a single pass of n steps, down from the nested scan's n squared additions."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored","progressRevision":"maximum-subarray-2026-08-08-name-cur-before-drawing-it"},"executionStyle":"solution-method"}
