{"id":"maximum-sum-subarray-of-size-k","title":"Maximum Sum Subarray of Size K","difficulty":"easy","patterns":["sliding-window"],"primaryConcept":"array-sliding-window-fixed","concepts":["array-sliding-window-fixed"],"problemForm":"intro","companies":["Amazon","Google","Meta","Microsoft"],"category":"arrays-strings","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"array-scalar","primaryParam":"nums","secondaryParam":"k","sizeMetric":"array-length","valueRange":{"min":-50,"max":50},"secondaryParams":{"k":{"strategy":"random-int","value":{"min":1,"max":8}}},"sizes":[8,16,32,64]},"description":"Given an integer array `nums` and an integer `k`, return the maximum sum of any contiguous subarray with exactly `k` elements.","examples":[{"input":"nums = [2,1,5,1,3,2], k = 3","output":"9","explanation":"The best window is [5,1,3], which sums to 9."},{"input":"nums = [2,3,4,1,5], k = 2","output":"7","explanation":"The best window is [3,4], which sums to 7."}],"constraints":[{"id":"1-k-len-nums-10-5","text":"1 <= k <= len(nums) <= 10^5"},{"id":"10-4-nums-i-10-4","text":"-10^4 <= nums[i] <= 10^4"}],"starterCode":"class Solution:\n    def maxSumSubarray(self, nums: list[int], k: int) -> int:\n        # Your code here\n        pass","functionName":"maxSumSubarray","testCases":[{"id":"1","input":{"nums":[2,1,5,1,3,2],"k":3},"expected":9,"description":"Canonical fixed-window example."},{"id":"2","input":{"nums":[2,3,4,1,5],"k":2},"expected":7,"description":"The best two-element window is in the middle."},{"id":"3","input":{"nums":[-5,-2,-3,-4],"k":2},"expected":-5,"description":"All negative values still choose the least negative window."},{"id":"4","input":{"nums":[4,2,1],"k":3},"expected":7,"description":"When k equals n, the only window is the whole array."},{"id":"5","input":{"nums":[1,-1,5,-2,3],"k":3},"expected":6,"description":"Mixed positive and negative values."},{"id":"h1","input":{"nums":[10,-2,3,4,-1,2],"k":4},"expected":15,"description":"Best window starts at index 0."},{"id":"h2","input":{"nums":[-1,4,-2,8,9],"k":2},"expected":17,"description":"Best window is the final two values."},{"id":"h3","input":{"nums":[0,0,0,0],"k":2},"expected":0,"description":"All-zero windows stay at zero."},{"id":"h4","input":{"nums":[-2,7,0,-1,4],"k":2},"expected":7,"description":"A positive spike in the middle wins the maximum."},{"id":"h5","input":{"nums":[100,-50,100,-50],"k":3},"expected":150,"description":"The best length-k window can span alternating large gains and losses."}],"hints":[{"level":1,"content":"All valid subarrays have the same length, so a fixed-size window fits naturally."},{"level":2,"content":"After computing the first window sum, each slide adds one new value and removes one old value."},{"level":3,"content":"Track the maximum window sum after each slide."}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which implementation should we use?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"brute-force","name":"Sum every window from scratch","summary":"For each start index, sum the next k values.","decisionReason":"It re-adds all k numbers for every window, including the overlap neighbouring windows share.","complexity":{"time":"O(n*k)","space":"O(1)"},"tradeoffs":["Runs in O(n*k) time and uses O(1) space."],"isOptimal":false},{"id":"fixed-window","name":"Slide one fixed window","summary":"Seed the first k values, then slide by adding the incoming value and removing the outgoing value.","decisionReason":"Carry one running window sum and adjust it by the element leaving and the one entering, so each slide is two operations instead of re-adding k numbers.","complexity":{"time":"O(n)","space":"O(1)"},"tradeoffs":["Runs in O(n) time and uses O(1) space."],"isOptimal":true}]},"codingCheckpoints":[{"id":"init-window","title":"Seed first window","description":"Compute the sum of the first k values and use it as the first best sum.","commonMistakes":["Starting best_sum at zero, which fails for all-negative arrays","Seeding fewer or more than k values"],"hint":"The first valid window is nums[0:k].","semanticSpec":{"intent":"Initialize the fixed-size window sum from the first k values.","doneWhen":"The code computes the first window sum and stores it before sliding.","shouldFailWhen":"This step should fail if there is no seeded fixed window.","roles":["window sum","window size","input array"],"mustProve":["The first k values seed the initial window sum."],"mustNotAccept":["Starting from an empty or zero-only best value without reading the first window."],"equivalentVariants":["Use sum(nums[:k]) or an explicit loop over the first k indices."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"sliding-window","fact":"seeds_first_fixed_window","scope":"init-window","readMode":"sliding-window-value-query-v1"}]}},{"id":"loop-start","title":"Start sliding after k","description":"Begin the sliding loop at the first index after the seeded window.","commonMistakes":["Starting at index 0 and double-counting values","Stopping before the final window"],"hint":"The first incoming value is at index k.","semanticSpec":{"intent":"Slide only after the first full window has already been seeded.","doneWhen":"The loop starts at k and continues through the array.","shouldFailWhen":"This step should fail if the sliding loop does not start at the window boundary.","roles":["loop index","window boundary"],"mustProve":["The sliding loop starts at the index equal to k."],"mustNotAccept":["Sliding from the beginning before the first window is complete."],"equivalentVariants":["Use a for-loop over range(k, len(nums))."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"sliding-window","fact":"starts_fixed_window_loop_at_bound","scope":"loop-start","readMode":"sliding-window-value-query-v1"}]}},{"id":"add-entering","title":"Add the entering value","description":"Add `nums[i]` to the running sum when index `i` enters the window.","commonMistakes":["Advancing the loop without adding `nums[i]`","Adding the outgoing value instead of the entering value"],"hint":"The loop index points to the new rightmost value. Add `nums[i]` to `window_sum`.","semanticSpec":{"intent":"Add the value entering at the right edge to the current fixed-window sum.","doneWhen":"The sliding loop adds `nums[i]` to `window_sum`.","shouldFailWhen":"This step should fail if the entering value is absent or comes from the wrong index.","roles":["incoming value","window sum"],"mustProve":["The value at the current sliding index is added to the window sum."],"mustNotAccept":["A sliding loop that never adds the entering value."],"equivalentVariants":["Use a separate addition or a combined delta expression."],"proofSnippets":[{"id":"py-max-sum-add-entering","language":"python","code":"def maxSumSubarray(nums, k):\n    window_sum = sum(nums[:k])\n    for i in range(k, len(nums)):\n        window_sum += nums[i]"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"sliding-window","fact":"adds_entering_value_to_window_state","scope":"add-entering","readMode":"sliding-window-value-query-v1"}]}},{"id":"remove-leaving","title":"Remove the leaving value","description":"Subtract `nums[i - k]` so the running sum still represents exactly `k` values.","commonMistakes":["Keeping the entering value without removing the expired one","Using `i - k + 1` instead of `i - k`"],"hint":"The value leaving the window is `k` positions behind index `i`.","semanticSpec":{"intent":"Remove the value that falls off the left edge of the fixed-size window.","doneWhen":"The sliding loop subtracts `nums[i - k]` from `window_sum`.","shouldFailWhen":"This step should fail if no value is removed or the outgoing index is wrong.","roles":["outgoing value","window size","window sum"],"mustProve":["The value `k` positions behind the sliding index is removed from the window sum."],"mustNotAccept":["A window sum that keeps growing after each slide."],"equivalentVariants":["Use a separate subtraction or a combined delta expression."],"proofSnippets":[{"id":"py-max-sum-remove-leaving","language":"python","code":"def maxSumSubarray(nums, k):\n    window_sum = sum(nums[:k])\n    for i in range(k, len(nums)):\n        window_sum += nums[i]\n        window_sum -= nums[i - k]"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"sliding-window","fact":"removes_leaving_value_from_window_state","scope":"remove-leaving","readMode":"sliding-window-value-query-v1"}]}},{"id":"track-max-sum","title":"Track best sum","description":"Update the best window sum after each slide.","commonMistakes":["Returning only the final window sum","Updating best_sum before sliding"],"hint":"Compare best_sum with the current window_sum after each update.","semanticSpec":{"intent":"Keep the maximum fixed-window sum seen so far.","doneWhen":"The code updates best_sum from window_sum during the sliding loop.","shouldFailWhen":"This step should fail if the best value is not tracked across windows.","roles":["best sum","window sum"],"mustProve":["The best state is updated from the current window sum."],"mustNotAccept":["Returning the last window without comparing earlier windows."],"equivalentVariants":["Use max(best_sum, window_sum) or an equivalent comparison branch."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"sliding-window","fact":"tracks_fixed_window_best","scope":"track-max-sum","readMode":"sliding-window-value-query-v1"}]}},{"id":"return-best","title":"Return best sum","description":"Return the maximum sum found across all length-k windows.","commonMistakes":["Returning window_sum instead of best_sum","Returning the window size"],"hint":"The tracked best sum is the answer.","semanticSpec":{"intent":"Return the terminal numeric answer.","doneWhen":"The method returns the tracked best sum.","shouldFailWhen":"This step should fail if the method returns a non-answer helper value.","roles":["best sum","terminal return"],"mustProve":["The terminal return yields the tracked numeric result."],"mustNotAccept":["Returning k or the input array."],"equivalentVariants":["Return the variable that stores the best sum."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"returns_terminal_numeric_state","readMode":"numeric-state-value-query-v1"}]}}],"slides":[{"id":"read-the-signal","chapter":"The window","kind":"info","eyebrow":"Read the problem","title":"The best block of k in a row","workspacePanel":"problem","body":["You get a list of numbers and a size k. Look at every block of k neighbours and report the largest block total.","The blocks overlap heavily as they slide. The obvious approach re-adds each block from scratch. Watch what that repeats."]},{"id":"brute-force","chapter":"The obvious way","kind":"code-trace","eyebrow":"The obvious way","title":"Re-add every block","summary":"Summing each block from its start finds the best one. Neighbouring blocks overlap heavily, and every block re-adds that shared middle. Watch how much of each sum repeats the one before it.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"best = 0\nfor start in range(len(nums) - k + 1):\n    total = 0\n    for j in range(start, start + k):\n        total += nums[j]\n    if total > best:\n        best = total\nreturn best","steps":[{"id":"first-block","title":"Add the first block","codeLine":5,"summary":"Block starting at 0 sums 2 + 1 + 5 = 8. Three additions for the first window.","state":{"nums":[2,1,5,1,3,2],"left":0,"right":2}},{"id":"second-block","title":"Re-add the next block from scratch","codeLine":2,"summary":"Block starting at 1 sums 1 + 5 + 1 = 7. The 1 and 5 were just added a moment ago, now added again.","state":{"nums":[2,1,5,1,3,2],"left":1,"right":3}},{"id":"overlap","title":"Each block re-sums the overlap","codeLine":4,"summary":"Every neighbouring block shares k - 1 numbers, yet each block totals all k from scratch. The shared middle is added over and over.","state":{"nums":[2,1,5,1,3,2],"left":2,"right":4}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"let best = 0;\nfor (let start = 0; start < ((nums.length - k) + 1); start++) {\n    let total = 0;\n    for (let j = start; j < (start + k); j++) {\n        total += nums[j];\n    }\n    if (total > best) {\n        best = total;\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":8,"8":11},"statementBundles":{"5":{"startLine":5,"endLine":6},"7":{"startLine":8,"endLine":10}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"let best = 0;\nfor (let start = 0; start < ((nums.length - k) + 1); start++) {\n    let total = 0;\n    for (let j = start; j < (start + k); j++) {\n        total += nums[j];\n    }\n    if (total > best) {\n        best = total;\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":8,"8":11},"statementBundles":{"5":{"startLine":5,"endLine":6},"7":{"startLine":8,"endLine":10}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int best = 0;\nfor (int start = 0; start < ((nums.size() - k) + 1); start++) {\n    int total = 0;\n    for (int j = start; j < (start + k); j++) {\n        total += nums.get(j);\n    }\n    if (total > best) {\n        best = total;\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":8,"8":11},"statementBundles":{"5":{"startLine":5,"endLine":6},"7":{"startLine":8,"endLine":10}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int best = 0;\nfor (int start = 0; start < nums.Count - k + 1; start++) {\n    int total = 0;\n    for (int j = start; j < start + k; j++) {\n        total += nums[j];\n    }\n    if (total > best) {\n        best = total;\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":8,"8":11},"statementBundles":{"5":{"startLine":5,"endLine":6},"7":{"startLine":8,"endLine":10}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"int best = 0;\nfor (int start = 0; start < ((nums.size() - k) + 1); start++) {\n    int total = 0;\n    for (int j = start; j < (start + k); j++) {\n        total += nums[j];\n    }\n    if (total > best) {\n        best = total;\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":8,"8":11},"statementBundles":{"5":{"startLine":5,"endLine":6},"7":{"startLine":8,"endLine":10}}}}},"body":["An outer loop fixes the block start; an inner loop adds all k numbers of that block."]},{"id":"repeated-work","chapter":"The obvious way","kind":"case-probe","eyebrow":"Name the waste","title":"What do two neighbouring blocks have in common?","workspacePanel":"trace","options":[{"id":"shared-middle","label":"All but one number: they share k - 1 elements","rationale":"Sliding by one drops the leftmost number and picks up one new number on the right. Everything between is identical and need not be re-added.","isCorrect":true},{"id":"nothing","label":"Nothing; each block is independent","rationale":"They overlap in k - 1 of their k numbers. Treating them as independent is exactly the re-adding the brute force does.","isCorrect":false},{"id":"the-max","label":"The same maximum element","rationale":"They may or may not share the max. What is guaranteed is the overlap of k - 1 positions, which is what saves the work.","isCorrect":false}],"answer":"All but one. Sliding one step keeps k - 1 numbers and swaps a single element, so the overlap never needs re-adding.","summary":"The block [2, 1, 5] is followed by [1, 5, 1]."},{"id":"slide-delta","chapter":"The idea","kind":"case-probe","eyebrow":"Find the update","title":"To turn one block sum into the next, what is the smallest change?","summary":"You have the sum of the current block and slide it one step right.","workspacePanel":"visualizer","options":[{"id":"subtract-add","label":"Subtract the number that left, add the number that entered","rationale":"The overlap is unchanged, so only the departing and arriving numbers matter. Two operations turn this block sum into the next.","isCorrect":true},{"id":"add-only","label":"Add the new number on the right","rationale":"Adding without subtracting grows the window past size k. The number sliding off the left must leave the sum too.","isCorrect":false},{"id":"resum","label":"Add up the k numbers again","rationale":"That is the brute-force work this is meant to avoid. The shared k - 1 numbers are already in the running sum.","isCorrect":false}],"answer":"Subtract the element leaving on the left and add the element entering on the right. The block sum updates in two steps, no matter how large k is.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"slide-delta-state","state":{"nums":[2,1,5,1,3,2],"left":0,"right":2,"windowSum":8,"best":8}}]}},{"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-structure","state":{"nums":[2,1,5,1,3,2],"left":0,"right":2,"windowSum":8,"best":8}}]}},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"One running sum, sliding right","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"dry-run-start","state":{"nums":[2,1,5,1,3,2],"left":0,"right":2,"windowSum":8,"best":8}}]},"body":["windowSum begins as the total of the first k numbers, and best begins there too.","Each slide subtracts the number dropping off the left and adds the number arriving on the right, keeping the window exactly k wide.","After each slide, best takes the larger of itself and the new windowSum."]},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the slide","title":"Trace the sliding sum","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"slide-one","state":{"nums":[2,1,5,1,3,2],"left":1,"right":3,"windowSum":7,"best":8}},{"id":"slide-two","state":{"nums":[2,1,5,1,3,2],"left":2,"right":4,"windowSum":9,"best":9}},{"id":"slide-three","state":{"nums":[2,1,5,1,3,2],"left":3,"right":5,"windowSum":6,"best":9}}]},"beats":[{"id":"slide-one","title":"After index 0 leaves, what is windowSum?","summary":"The 2 at index 0 leaves; the 1 at index 3 enters.","prompt":"The window moves from [2,1,5] to [1,5,1].","options":[{"id":"seven","label":"7","rationale":"Subtract the departing 2 and add the entering 1: 8 - 2 + 1 = 7. No need to re-add the shared 1 and 5.","isCorrect":true},{"id":"nine","label":"9, just adding the new 1","rationale":"Adding without subtracting leaves the old 2 in the sum, making a window of size 4. The 2 must leave.","isCorrect":false},{"id":"eight","label":"8, unchanged","rationale":"The window did change: it dropped a 2 and gained a 1, a net of -1. The sum becomes 7.","isCorrect":false}],"answer":"7. windowSum = 8 - 2 + 1 = 7. best stays 8 since 7 is smaller."},{"id":"slide-two","title":"Now 1 leaves and 3 enters. windowSum was 7. What is it, and does best change?","summary":"The window slides to [5, 1, 3].","prompt":"Index 1 (value 1) leaves; index 4 (value 3) enters.","options":[{"id":"nine-best","label":"9, and best rises to 9","rationale":"7 - 1 + 3 = 9, the largest block yet, so best climbs from 8 to 9.","isCorrect":true},{"id":"nine-no-best","label":"9, but best stays 8","rationale":"9 beats the old best of 8, so best must update. It becomes 9.","isCorrect":false},{"id":"ten","label":"10","rationale":"Only one number leaves and one enters: 7 - 1 + 3 = 9, not 10.","isCorrect":false}],"answer":"9. windowSum = 7 - 1 + 3 = 9, and best rises to 9."},{"id":"slide-three","title":"The final move gives windowSum 6. Does the answer change?","summary":"5 leaves and 2 enters, for the block [1, 3, 2].","prompt":"windowSum becomes 9 - 5 + 2 = 6.","options":[{"id":"stays-nine","label":"No, best stays 9","rationale":"6 is below the best of 9, so best holds. The window has reached the end, and 9 is the answer.","isCorrect":true},{"id":"drops","label":"best drops to 6","rationale":"best only ever rises. A smaller block cannot lower the best already found.","isCorrect":false},{"id":"continues","label":"The window slides once more","rationale":"The window now ends at the last index, so there is no further slide. best is final at 9.","isCorrect":false}],"answer":"No. 6 is below 9, so best stays 9, the final answer."}]},{"id":"no-subtract-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Can you just keep adding the next number?","summary":"Adding the arriving number to the running sum each step feels like sliding the window forward, and it gives the right first block. But nothing ever leaves, so the window silently grows. Watch the sum past the first slide.","workspacePanel":"trace","pitfall":"The loop below adds each new number to the running sum but never subtracts the one leaving.","whyItMatters":"A fixed window must lose its left element as it gains a right one. Without the subtraction the sum becomes a growing prefix total, so it reports the whole array. Subtract nums[i - k] each time you add nums[i].","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"window_sum = 0\nfor j in range(k):\n    window_sum += nums[j]\nbest = window_sum\nfor i in range(k, len(nums)):\n    window_sum += nums[i]\n    if window_sum > best:\n        best = window_sum\nreturn best","steps":[{"id":"first-ok","title":"The first block is right","codeLine":4,"summary":"nums = [2,1,5,1,3,2], k = 3. The first block sums to 8, and best starts at 8. So far so good.","state":{"nums":[2,1,5,1,3,2],"left":0,"right":2,"windowSum":8,"best":8}},{"id":"grows","title":"The window only grows","codeLine":6,"summary":"At index 3 it adds 1 to get 9, then 3 to get 12, then 2 to get 14, never dropping the left numbers. The window is now the whole array.","state":{"nums":[2,1,5,1,3,2],"left":0,"right":5,"windowSum":14,"best":14}},{"id":"wrong-total","title":"It returns the whole-array sum","codeLine":9,"summary":"best ends at 14, the total of all six numbers. The best block of 3 sums to 9.","state":{"nums":[2,1,5,1,3,2],"left":0,"right":5,"windowSum":14,"best":14}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"let windowSum = 0;\nfor (let j = 0; j < k; j++) {\n    windowSum += nums[j];\n}\nlet best = windowSum;\nfor (let i = k; i < nums.length; i++) {\n    windowSum += nums[i];\n    if (windowSum > best) {\n        best = windowSum;\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":8,"8":9,"9":12},"statementBundles":{"3":{"startLine":3,"endLine":4},"8":{"startLine":9,"endLine":11}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"let windowSum = 0;\nfor (let j = 0; j < k; j++) {\n    windowSum += nums[j];\n}\nlet best = windowSum;\nfor (let i = k; i < nums.length; i++) {\n    windowSum += nums[i];\n    if (windowSum > best) {\n        best = windowSum;\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":8,"8":9,"9":12},"statementBundles":{"3":{"startLine":3,"endLine":4},"8":{"startLine":9,"endLine":11}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int windowSum = 0;\nfor (int j = 0; j < k; j++) {\n    windowSum += nums.get(j);\n}\nint best = windowSum;\nfor (int i = k; i < nums.size(); i++) {\n    windowSum += nums.get(i);\n    if (windowSum > best) {\n        best = windowSum;\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":8,"8":9,"9":12},"statementBundles":{"3":{"startLine":3,"endLine":4},"8":{"startLine":9,"endLine":11}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int windowSum = 0;\nfor (int j = 0; j < k; j++) {\n    windowSum += nums[j];\n}\nint best = windowSum;\nfor (int i = k; i < nums.Count; i++) {\n    windowSum += nums[i];\n    if (windowSum > best) {\n        best = windowSum;\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":8,"8":9,"9":12},"statementBundles":{"3":{"startLine":3,"endLine":4},"8":{"startLine":9,"endLine":11}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"int window_sum = 0;\nfor (int j = 0; j < k; j++) {\n    window_sum += nums[j];\n}\nint best = window_sum;\nfor (int i = k; i < nums.size(); i++) {\n    window_sum += nums[i];\n    if (window_sum > best) {\n        best = window_sum;\n    }\n}\nreturn best;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":8,"8":9,"9":12},"statementBundles":{"3":{"startLine":3,"endLine":4},"8":{"startLine":9,"endLine":11}}}}}},{"id":"edge-case-intro","kind":"info","chapter":"Edge cases","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","body":["Holding one window sum and adjusting it by the one number entering and the one leaving found the best block in a single pass.","Now bound the window itself: a window as wide as the whole list, and a window of size one."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"intro-state","state":{"nums":[2,1,5,1,3,2],"left":0,"right":2,"windowSum":8,"best":8}}]}},{"id":"whole-array-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"What if k equals the length of the list?","summary":"nums = [2, 1, 5] and k = 3.","workspacePanel":"visualizer","options":[{"id":"whole-sum","label":"8, the total of the only block","rationale":"The first window already spans the whole list, so there is nothing to slide into. best is just that single block sum, 8.","isCorrect":true},{"id":"max-element","label":"5, the largest element","rationale":"The block sums all k numbers. With k equal to the length, the answer is the total.","isCorrect":false},{"id":"error","label":"There is no valid window","rationale":"A window of size k fits exactly once when k equals the length. That single window is the answer.","isCorrect":false}],"answer":"8. The window covers the entire list, so the only block is the whole thing and the loop never slides.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"whole-array-state","state":{"nums":[2,1,5],"left":0,"right":2,"windowSum":8,"best":8}}]}},{"id":"k-one-edge","chapter":"Edge cases","kind":"case-probe","eyebrow":"Stress the rule","title":"What does k = 1 ask for?","summary":"nums = [2, 1, 5, 3] and k = 1.","workspacePanel":"visualizer","options":[{"id":"max-element","label":"5, the largest single element","rationale":"Each window is one number, so sliding just compares single values. The best block of one is the maximum element.","isCorrect":true},{"id":"first","label":"2, the first element","rationale":"The window slides across all of them, keeping the best. The largest single value, 5, wins.","isCorrect":false},{"id":"sum","label":"The sum of the list","rationale":"A window of size 1 holds one number, not all of them. The best is the maximum element.","isCorrect":false}],"answer":"5. With k = 1 each window is a single number, so the best block is just the largest element.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"k-one-edge-state","state":{"nums":[2,1,5,3],"left":2,"right":2,"windowSum":5,"best":5}}]}},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"One window sum, sliding right","summary":"Subtract the number leaving exactly as you add the one entering.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-to-code-start","state":{"nums":[2,1,5,1,3,2],"left":0,"right":2,"windowSum":8,"best":8}}]},"body":["Add the first k numbers as the window sum. Then slide it along: each step drop the number falling off the left, add the new one on the right, and keep the largest sum seen."]},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the fixed-window slide","eyebrow":"Code the rule","summary":"Seed the sum of the first `k` values and start the loop at index `k`. Add `nums[i]`, remove `nums[i - k]`, update the largest sum, and return it after the loop.","workspacePanel":"code","checkpoints":[{"id":"init-window","title":"Seed first window","description":"Compute the sum of the first k values and use it as the first best sum.","commonMistakes":["Starting best_sum at zero, which fails for all-negative arrays","Seeding fewer or more than k values"],"hint":"The first valid window is nums[0:k].","semanticSpec":{"intent":"Initialize the fixed-size window sum from the first k values.","doneWhen":"The code computes the first window sum and stores it before sliding.","shouldFailWhen":"This step should fail if there is no seeded fixed window.","roles":["window sum","window size","input array"],"mustProve":["The first k values seed the initial window sum."],"mustNotAccept":["Starting from an empty or zero-only best value without reading the first window."],"equivalentVariants":["Use sum(nums[:k]) or an explicit loop over the first k indices."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"sliding-window","fact":"seeds_first_fixed_window","scope":"init-window","readMode":"sliding-window-value-query-v1"}]}},{"id":"loop-start","title":"Start sliding after k","description":"Begin the sliding loop at the first index after the seeded window.","commonMistakes":["Starting at index 0 and double-counting values","Stopping before the final window"],"hint":"The first incoming value is at index k.","semanticSpec":{"intent":"Slide only after the first full window has already been seeded.","doneWhen":"The loop starts at k and continues through the array.","shouldFailWhen":"This step should fail if the sliding loop does not start at the window boundary.","roles":["loop index","window boundary"],"mustProve":["The sliding loop starts at the index equal to k."],"mustNotAccept":["Sliding from the beginning before the first window is complete."],"equivalentVariants":["Use a for-loop over range(k, len(nums))."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"sliding-window","fact":"starts_fixed_window_loop_at_bound","scope":"loop-start","readMode":"sliding-window-value-query-v1"}]}},{"id":"add-entering","title":"Add the entering value","description":"Add `nums[i]` to the running sum when index `i` enters the window.","commonMistakes":["Advancing the loop without adding `nums[i]`","Adding the outgoing value instead of the entering value"],"hint":"The loop index points to the new rightmost value. Add `nums[i]` to `window_sum`.","semanticSpec":{"intent":"Add the value entering at the right edge to the current fixed-window sum.","doneWhen":"The sliding loop adds `nums[i]` to `window_sum`.","shouldFailWhen":"This step should fail if the entering value is absent or comes from the wrong index.","roles":["incoming value","window sum"],"mustProve":["The value at the current sliding index is added to the window sum."],"mustNotAccept":["A sliding loop that never adds the entering value."],"equivalentVariants":["Use a separate addition or a combined delta expression."],"proofSnippets":[{"id":"py-max-sum-add-entering","language":"python","code":"def maxSumSubarray(nums, k):\n    window_sum = sum(nums[:k])\n    for i in range(k, len(nums)):\n        window_sum += nums[i]"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"sliding-window","fact":"adds_entering_value_to_window_state","scope":"add-entering","readMode":"sliding-window-value-query-v1"}]}},{"id":"remove-leaving","title":"Remove the leaving value","description":"Subtract `nums[i - k]` so the running sum still represents exactly `k` values.","commonMistakes":["Keeping the entering value without removing the expired one","Using `i - k + 1` instead of `i - k`"],"hint":"The value leaving the window is `k` positions behind index `i`.","semanticSpec":{"intent":"Remove the value that falls off the left edge of the fixed-size window.","doneWhen":"The sliding loop subtracts `nums[i - k]` from `window_sum`.","shouldFailWhen":"This step should fail if no value is removed or the outgoing index is wrong.","roles":["outgoing value","window size","window sum"],"mustProve":["The value `k` positions behind the sliding index is removed from the window sum."],"mustNotAccept":["A window sum that keeps growing after each slide."],"equivalentVariants":["Use a separate subtraction or a combined delta expression."],"proofSnippets":[{"id":"py-max-sum-remove-leaving","language":"python","code":"def maxSumSubarray(nums, k):\n    window_sum = sum(nums[:k])\n    for i in range(k, len(nums)):\n        window_sum += nums[i]\n        window_sum -= nums[i - k]"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"sliding-window","fact":"removes_leaving_value_from_window_state","scope":"remove-leaving","readMode":"sliding-window-value-query-v1"}]}},{"id":"track-max-sum","title":"Track best sum","description":"Update the best window sum after each slide.","commonMistakes":["Returning only the final window sum","Updating best_sum before sliding"],"hint":"Compare best_sum with the current window_sum after each update.","semanticSpec":{"intent":"Keep the maximum fixed-window sum seen so far.","doneWhen":"The code updates best_sum from window_sum during the sliding loop.","shouldFailWhen":"This step should fail if the best value is not tracked across windows.","roles":["best sum","window sum"],"mustProve":["The best state is updated from the current window sum."],"mustNotAccept":["Returning the last window without comparing earlier windows."],"equivalentVariants":["Use max(best_sum, window_sum) or an equivalent comparison branch."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"sliding-window","fact":"tracks_fixed_window_best","scope":"track-max-sum","readMode":"sliding-window-value-query-v1"}]}},{"id":"return-best","title":"Return best sum","description":"Return the maximum sum found across all length-k windows.","commonMistakes":["Returning window_sum instead of best_sum","Returning the window size"],"hint":"The tracked best sum is the answer.","semanticSpec":{"intent":"Return the terminal numeric answer.","doneWhen":"The method returns the tracked best sum.","shouldFailWhen":"This step should fail if the method returns a non-answer helper value.","roles":["best sum","terminal return"],"mustProve":["The terminal return yields the tracked numeric result."],"mustNotAccept":["Returning k or the input array."],"equivalentVariants":["Return the variable that stores the best sum."]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"returns_terminal_numeric_state","readMode":"numeric-state-value-query-v1"}]}}]},{"id":"complete","kind":"complete","chapter":"Code","title":"What to carry forward","eyebrow":"Take it with you","summary":"Slide a window of size k by adding the entering value and dropping the leaving one.","workspacePanel":"code","body":["A fixed-size window’s sum updates in constant time: add the new right element, subtract the old left element, with no re-summing.","Track the best sum as the window slides from left to right."],"takeaways":[{"title":"The window updates, it never rebuilds","body":"Add one, drop one keeps the sum current in constant time, turning a nested re-sum into a single pass."},{"title":"k = 1 is just the maximum","body":"A window of one reduces to the largest single element, the boundary the slide handles for free."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"},"starterFunctionName":"maxSumSubarray","tags":["Array","Sliding Window","Fixed Window"]}
