{"id":411,"date":"2025-06-26T23:09:58","date_gmt":"2025-06-26T17:39:58","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=411"},"modified":"2025-06-26T23:09:59","modified_gmt":"2025-06-26T17:39:59","slug":"maximum-subarray-kadanes-algorithm","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/maximum-subarray-kadanes-algorithm\/","title":{"rendered":"Maximum Subarray | Kadane&#8217;s Algorithm | From Brute Force to Optimal"},"content":{"rendered":"\n<p>Explore the Maximum Subarray problem with a brute-force triple loop, a quadratic improvement, and the optimal Kadane\u2019s Algorithm, all with intuition, fully-commented Python, dry runs, and complexity analysis.<\/p>\n\n\n\n<p>Here&#8217;s the [<strong><a href=\"https:\/\/leetcode.com\/problems\/maximum-subarray\/description\/\" target=\"_blank\" rel=\"noreferrer noopener\"><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-purple-color\"><span style=\"text-decoration: underline;\">Problem Link<\/span><\/mark><\/a><\/strong>] to begin with.<\/p>\n\n\n<div style=\"max-width: -moz-fit-content; \" class=\"wp-block-ub-table-of-contents-block ub_table-of-contents ub_table-of-contents-collapsed\" id=\"ub_table-of-contents-48cbe96e-f85e-4ec2-a142-22c4f0b4e235\" data-linktodivider=\"false\" data-showtext=\"show\" data-hidetext=\"hide\" data-scrolltype=\"auto\" data-enablesmoothscroll=\"true\" data-initiallyhideonmobile=\"false\" data-initiallyshow=\"false\"><div class=\"ub_table-of-contents-header-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-header\" style=\"text-align: left; \">\n\t\t\t\t<div class=\"ub_table-of-contents-title\">Contents:<\/div>\n\t\t\t\t<div class=\"ub_table-of-contents-header-toggle\">\n\t\t\t<div class=\"ub_table-of-contents-toggle\" style=\"\">\n\t\t\t\u00a0[<a class=\"ub_table-of-contents-toggle-link\" href=\"#\" style=\"\">show<\/a>]\n\t\t\t<\/div>\n\t\t<\/div>\n\t\t\t<\/div>\n\t\t<\/div><div class=\"ub_table-of-contents-extra-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-container ub_table-of-contents-1-column ub-hide\">\n\t\t\t\t<ul style=\"\"><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/maximum-subarray-kadanes-algorithm\/#0-common-example-for-all-sections\" style=\"\">\ud83d\udcda Common Example for All Sections<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/maximum-subarray-kadanes-algorithm\/#1-1%EF%B8%8F%E2%83%A3-brute-force-%E2%80%93-triple-loop\" style=\"\">1\ufe0f\u20e3 Brute Force \u2013 Triple Loop<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/maximum-subarray-kadanes-algorithm\/#2-11-intuition-amp-approach\" style=\"\">1.1 Intuition &amp; Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/maximum-subarray-kadanes-algorithm\/#3-12-python-code-with-comments\" style=\"\">1.2 Python Code (with comments)<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/maximum-subarray-kadanes-algorithm\/#4-13-dry-run-first-five-iterations\" style=\"\">1.3 Dry Run (first five iterations)<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/maximum-subarray-kadanes-algorithm\/#5-14-complexity\" style=\"\">1.4 Complexity<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/maximum-subarray-kadanes-algorithm\/#6-2%EF%B8%8F%E2%83%A3-better-brute-%E2%80%93-double-loop\" style=\"\">2\ufe0f\u20e3 Better Brute \u2013 Double Loop<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/maximum-subarray-kadanes-algorithm\/#7-21-intuition-amp-approach\" style=\"\">2.1 Intuition &amp; Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/maximum-subarray-kadanes-algorithm\/#8-22-python-code-with-comments\" style=\"\">2.2 Python Code (with comments)<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/maximum-subarray-kadanes-algorithm\/#9-23-dry-run-first-start-index-i-0-\" style=\"\">2.3 Dry Run (first start index i = 0)<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/maximum-subarray-kadanes-algorithm\/#10-24-complexity\" style=\"\">2.4 Complexity<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/maximum-subarray-kadanes-algorithm\/#11-3%EF%B8%8F%E2%83%A3-optimal-%E2%80%93-kadane%E2%80%99s-algorithm-\" style=\"\">3\ufe0f\u20e3 Optimal \u2013 Kadane\u2019s Algorithm<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/maximum-subarray-kadanes-algorithm\/#12-31-core-insight\" style=\"\">3.1 Core Insight<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/maximum-subarray-kadanes-algorithm\/#13-32-algorithm-steps\" style=\"\">3.2 Algorithm Steps<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/maximum-subarray-kadanes-algorithm\/#14-33-python-code-with-comments\" style=\"\">3.3 Python Code (with comments)<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/maximum-subarray-kadanes-algorithm\/#15-34-dry-run-on-example-array\" style=\"\">3.4 Dry Run on Example Array<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/maximum-subarray-kadanes-algorithm\/#16-35-complexity\" style=\"\">3.5 Complexity<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/maximum-subarray-kadanes-algorithm\/#17-%E2%9C%A8-summary-table\" style=\"\">\u2728 Summary Table<\/a><\/li><\/ul>\n\t\t\t<\/div>\n\t\t<\/div><\/div>\n\n\n<p><em>Find the contiguous slice of an array whose elements add up to the largest possible sum.<\/em><\/p>\n\n\n\n<p>We\u2019ll walk through <strong>three distinct solutions<\/strong>, each in its own self-contained section so you can master them one at a time:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Section<\/th><th>Time<\/th><th>Space<\/th><th>Core idea<\/th><\/tr><\/thead><tbody><tr><td>1. Brute Force (Triple Loop)<\/td><td><code>O(n\u00b3)<\/code><\/td><td><code>O(1)<\/code><\/td><td>Check every subarray, add fresh each time<\/td><\/tr><tr><td>2. Better Brute (Double Loop)<\/td><td><code>O(n\u00b2)<\/code><\/td><td><code>O(1)<\/code><\/td><td>Carry a running sum inside the inner loop<\/td><\/tr><tr><td>3. Optimal \u2013 Kadane<\/td><td><code>O(n)<\/code><\/td><td><code>O(1)<\/code><\/td><td>Drop negative baggage as you scan<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"0-common-example-for-all-sections\">Common Example for All Sections<\/h2>\n\n\n\n<p><code>nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]<\/code><br>The best subarray is <code>[4, -1, 2, 1]<\/code> with sum <strong>6<\/strong>.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"1-1%EF%B8%8F%E2%83%A3-brute-force-%E2%80%93-triple-loop\">1. Brute Force \u2013 Triple Loop<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"2-11-intuition-amp-approach\">1.1 Intuition &amp; Approach<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Pick every start index <code>i<\/code>.<\/li>\n\n\n\n<li>Pick every end index <code>j \u2265 i<\/code>.<\/li>\n\n\n\n<li>Add every element from <code>i<\/code> to <code>j<\/code> in a third loop.<\/li>\n\n\n\n<li>Keep the maximum sum seen.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"3-12-python-code-with-comments\">1.2 Python Code (with comments)<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"class Solution:\n    def maxSubArray(self, nums: List[int]) -&gt; int:\n        maxi = float(&quot;-inf&quot;)            # global best\n        n = len(nums)\n        for i in range(n):              # start index\n            for j in range(i, n):       # end index\n                cur_sum = 0\n                for k in range(i, j + 1):  # walk i\u2026j\n                    cur_sum += nums[k]\n                maxi = max(maxi, cur_sum)  # update best\n        return maxi\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">maxSubArray<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">nums<\/span><span style=\"color: #D4D4D4\">: List[<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">]) -&gt; <\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        maxi = <\/span><span style=\"color: #4EC9B0\">float<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;-inf&quot;<\/span><span style=\"color: #D4D4D4\">)            <\/span><span style=\"color: #6A9955\"># global best<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        n = <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(nums)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> i <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(n):              <\/span><span style=\"color: #6A9955\"># start index<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> j <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(i, n):       <\/span><span style=\"color: #6A9955\"># end index<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                cur_sum = <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> k <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(i, j + <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">):  <\/span><span style=\"color: #6A9955\"># walk i\u2026j<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    cur_sum += nums[k]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                maxi = <\/span><span style=\"color: #DCDCAA\">max<\/span><span style=\"color: #D4D4D4\">(maxi, cur_sum)  <\/span><span style=\"color: #6A9955\"># update best<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> maxi<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"4-13-dry-run-first-five-iterations\">1.3 Dry Run (first five iterations)<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th><code>i<\/code><\/th><th><code>j<\/code><\/th><th><code>cur_sum<\/code><\/th><th><code>maxi<\/code><\/th><\/tr><\/thead><tbody><tr><td>0<\/td><td>0<\/td><td>-2<\/td><td>-2<\/td><\/tr><tr><td>0<\/td><td>1<\/td><td>-1<\/td><td>-1<\/td><\/tr><tr><td>0<\/td><td>2<\/td><td>-4<\/td><td>-1<\/td><\/tr><tr><td>0<\/td><td>3<\/td><td><strong>0<\/strong><\/td><td><strong>0<\/strong><\/td><\/tr><tr><td>0<\/td><td>4<\/td><td>-1<\/td><td>0<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>Eventually <code>maxi<\/code> becomes <strong>6<\/strong>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"5-14-complexity\">1.4 Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time<\/strong> <code>O(n\u00b3)<\/code> \u2013 three nested loops<\/li>\n\n\n\n<li><strong>Space<\/strong> <code>O(1)<\/code> \u2013 only scalars<\/li>\n<\/ul>\n\n\n\n<p>Good for teaching but impractical beyond tiny arrays.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"6-2%EF%B8%8F%E2%83%A3-better-brute-%E2%80%93-double-loop\">2. Better Brute \u2013 Double Loop<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"7-21-intuition-amp-approach\">2.1 Intuition &amp; Approach<\/h3>\n\n\n\n<p>Reuse the running sum <code>s<\/code> as the end index <code>j<\/code> expands; no need to recompute from scratch.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"8-22-python-code-with-comments\">2.2 Python Code (with comments)<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"class Solution:\n    def maxSubArray(self, nums: List[int]) -&gt; int:\n        maxi = float(&quot;-inf&quot;)\n        n = len(nums)\n        for i in range(n):          # start index\n            s = 0\n            for j in range(i, n):   # extend to the right\n                s += nums[j]        # add current element\n                maxi = max(maxi, s) # update best\n        return maxi\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">maxSubArray<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">nums<\/span><span style=\"color: #D4D4D4\">: List[<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">]) -&gt; <\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        maxi = <\/span><span style=\"color: #4EC9B0\">float<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;-inf&quot;<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        n = <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(nums)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> i <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(n):          <\/span><span style=\"color: #6A9955\"># start index<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            s = <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> j <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(i, n):   <\/span><span style=\"color: #6A9955\"># extend to the right<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                s += nums[j]        <\/span><span style=\"color: #6A9955\"># add current element<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                maxi = <\/span><span style=\"color: #DCDCAA\">max<\/span><span style=\"color: #D4D4D4\">(maxi, s) <\/span><span style=\"color: #6A9955\"># update best<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> maxi<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"9-23-dry-run-first-start-index-i-0-\">2.3 Dry Run (first start index <code>i = 0<\/code>)<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th><code>j<\/code><\/th><th><code>s<\/code> after <code>+= nums[j]<\/code><\/th><th><code>maxi<\/code><\/th><\/tr><\/thead><tbody><tr><td>0<\/td><td>-2<\/td><td>-2<\/td><\/tr><tr><td>1<\/td><td>-1<\/td><td>-1<\/td><\/tr><tr><td>2<\/td><td>-4<\/td><td>-1<\/td><\/tr><tr><td>3<\/td><td><strong>0<\/strong><\/td><td><strong>0<\/strong><\/td><\/tr><tr><td>4<\/td><td>-1<\/td><td>0<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"10-24-complexity\">2.4 Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time<\/strong> <code>O(n\u00b2)<\/code> \u2013 one loop dropped<\/li>\n\n\n\n<li><strong>Space<\/strong> <code>O(1)<\/code><\/li>\n<\/ul>\n\n\n\n<p>A huge speed-up over triple loops, but still slow for <code>n<\/code> \u2248 10\u2075.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"11-3%EF%B8%8F%E2%83%A3-optimal-%E2%80%93-kadane%E2%80%99s-algorithm-\">3. Optimal \u2013 <strong>Kadane\u2019s Algorithm<\/strong><\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"12-31-core-insight\">3.1 Core Insight<\/h3>\n\n\n\n<p><em>Maintain the best <strong>prefix sum<\/strong> ending at the current index.<\/em><br>If that prefix becomes negative, starting fresh at the next index can only help.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"13-32-algorithm-steps\">3.2 Algorithm Steps<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Let <code>curSum = 0<\/code>, <code>maxi = -\u221e<\/code>.<\/li>\n\n\n\n<li>For each element <code>num<\/code> in <code>nums<\/code>\n<ul class=\"wp-block-list\">\n<li><code>curSum += num<\/code><\/li>\n\n\n\n<li><code>maxi = max(maxi, curSum)<\/code><\/li>\n\n\n\n<li>If <code>curSum &lt; 0<\/code>, reset <code>curSum = 0<\/code> (drop negative prefix).<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><code>maxi<\/code> now holds the answer.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"14-33-python-code-with-comments\">3.3 Python Code (with comments)<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"class Solution:\n    def maxSubArray(self, nums: List[int]) -&gt; int:\n        maxi = float(&quot;-inf&quot;)   # best seen so far\n        curSum = 0             # sum of current window\n\n        for num in nums:\n            curSum += num          # extend window\n            maxi = max(maxi, curSum)\n\n            if curSum &lt; 0:         # negative drag \u2013 cut here\n                curSum = 0\n\n        return maxi\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">maxSubArray<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">nums<\/span><span style=\"color: #D4D4D4\">: List[<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">]) -&gt; <\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        maxi = <\/span><span style=\"color: #4EC9B0\">float<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;-inf&quot;<\/span><span style=\"color: #D4D4D4\">)   <\/span><span style=\"color: #6A9955\"># best seen so far<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        curSum = <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">             <\/span><span style=\"color: #6A9955\"># sum of current window<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> num <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> nums:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            curSum += num          <\/span><span style=\"color: #6A9955\"># extend window<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            maxi = <\/span><span style=\"color: #DCDCAA\">max<\/span><span style=\"color: #D4D4D4\">(maxi, curSum)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> curSum &lt; <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">:         <\/span><span style=\"color: #6A9955\"># negative drag \u2013 cut here<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                curSum = <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> maxi<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"15-34-dry-run-on-example-array\">3.4 Dry Run on Example Array<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Index<\/th><th><code>num<\/code><\/th><th><code>curSum<\/code> after <code>+=<\/code><\/th><th><code>maxi<\/code><\/th><th>Action<\/th><\/tr><\/thead><tbody><tr><td>0<\/td><td>-2<\/td><td>-2<\/td><td>-2<\/td><td>reset (<code>curSum = 0<\/code>)<\/td><\/tr><tr><td>1<\/td><td>1<\/td><td>1<\/td><td>1<\/td><td>keep<\/td><\/tr><tr><td>2<\/td><td>-3<\/td><td>-2<\/td><td>1<\/td><td>reset<\/td><\/tr><tr><td>3<\/td><td>4<\/td><td>4<\/td><td><strong>4<\/strong><\/td><td>keep<\/td><\/tr><tr><td>4<\/td><td>-1<\/td><td>3<\/td><td><strong>4<\/strong><\/td><td>keep<\/td><\/tr><tr><td>5<\/td><td>2<\/td><td>5<\/td><td><strong>5<\/strong><\/td><td>keep<\/td><\/tr><tr><td>6<\/td><td>1<\/td><td>6<\/td><td><strong>6<\/strong><\/td><td>keep<\/td><\/tr><tr><td>7<\/td><td>-5<\/td><td>1<\/td><td>6<\/td><td>keep<\/td><\/tr><tr><td>8<\/td><td>4<\/td><td><strong>5<\/strong><\/td><td>6<\/td><td>done<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"16-35-complexity\">3.5 Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time<\/strong> <code>O(n)<\/code> \u2013 one pass<\/li>\n\n\n\n<li><strong>Space<\/strong> <code>O(1)<\/code> \u2013 two scalars<\/li>\n<\/ul>\n\n\n\n<p><strong>Kadane\u2019s Algorithm<\/strong> is optimal for this problem.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"17-%E2%9C%A8-summary-table\">Summary Table<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Solution<\/th><th>Time<\/th><th>Space<\/th><th>When to use<\/th><\/tr><\/thead><tbody><tr><td>Triple Loop<\/td><td><code>O(n\u00b3)<\/code><\/td><td><code>O(1)<\/code><\/td><td>Teaching brute force<\/td><\/tr><tr><td>Double Loop<\/td><td><code>O(n\u00b2)<\/code><\/td><td><code>O(1)<\/code><\/td><td>Small <code>n<\/code> (\u2272 1 000)<\/td><\/tr><tr><td><strong>Kadane<\/strong><\/td><td><strong>O(n)<\/strong><\/td><td><strong>O(1)<\/strong><\/td><td>Any real input (LeetCode, interviews)<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>Remember the focus phrase\u2014<strong>Maximum Subarray | Kadane&#8217;s Algorithm<\/strong>\u2014and reach for Kadane to ace this classic interview favorite.<\/p>\n\n\n\n<div class=\"wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button\"><a class=\"wp-block-button__link wp-element-button\" href=\"https:\/\/codeanddebug.in\/course\/zero-to-hero-python-dsa\" target=\"_blank\" rel=\"noreferrer noopener\">Join our Advance DSA COURSE<\/a><\/div>\n<\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><em>For any changes to the article, kindly email at <a href=\"mailto:code@codeanddebug.in\" target=\"_blank\" rel=\"noreferrer noopener\">code@codeanddebug.in<\/a> or contact us at <a href=\"tel:+91-9712928220\" target=\"_blank\" rel=\"noreferrer noopener\">+91-9712928220<\/a>.<\/em><\/p>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Explore the Maximum Subarray problem with a brute-force triple loop, a quadratic improvement, and the optimal Kadane\u2019s Algorithm, all with intuition, fully-commented Python, dry runs, and complexity analysis. Here&#8217;s the [Problem Link] to begin with. Find the contiguous slice of an array whose elements add up to the largest possible sum. We\u2019ll walk through three<\/p>\n","protected":false},"author":1,"featured_media":413,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3,4],"tags":[7,8],"class_list":{"0":"post-411","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-data-structures-and-algorithm","8":"category-beginner","9":"tag-array","10":"tag-easy"},"featured_image_src":"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2025\/06\/maximum-subarray-kadanes-algorithm-featured-image.png","author_info":{"display_name":"codeanddebug","author_link":"https:\/\/codeanddebug.in\/blog\/author\/codeanddebug\/"},"_links":{"self":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/411","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/comments?post=411"}],"version-history":[{"count":1,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/411\/revisions"}],"predecessor-version":[{"id":414,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/411\/revisions\/414"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/413"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=411"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=411"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=411"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}