Size of The Subarray With Maximum Sum (original) (raw)

Last Updated : 17 May, 2023

Given an array arr[] of size N, the task is to find the length of the subarray having maximum sum.

Examples :

Input : a[] = {1, -2, 1, 1, -2, 1} Output : Length of the subarray is 2 Explanation : Subarray with consecutive elements and maximum sum will be {1, 1}. So length is 2

Input : ar[] = { -2, -3, 4, -1, -2, 1, 5, -3 } Output : Length of the subarray is 5 Explanation : Subarray with consecutive elements and maximum sum will be {4, -1, -2, 1, 5}.

Method 1: This problem is mainly a variation of Largest Sum Contiguous Subarray Problem.
The idea is to update starting index whenever the sum ending here becomes less than 0.

Below is the implementation of the above approach:

C++ `

// C++ program to print length of the largest // contiguous array sum #include<bits/stdc++.h> using namespace std;

int maxSubArraySum(int a[], int size) { int max_so_far = INT_MIN, max_ending_here = 0, start =0, end = 0, s=0;

for (int i=0; i< size; i++ )
{
    max_ending_here += a[i];

    if (max_so_far < max_ending_here)
    {
        max_so_far = max_ending_here;
        start = s;
        end = i;
    }

    if (max_ending_here < 0)
    {
        max_ending_here = 0;
        s = i + 1;
    }
}

return (end - start + 1);

}

/Driver program to test maxSubArraySum/ int main() { int a[] = {-2, -3, 4, -1, -2, 1, 5, -3}; int n = sizeof(a)/sizeof(a[0]); cout << maxSubArraySum(a, n); return 0; }

Java

// Java program to print length of the largest // contiguous array sum import java.io.*;

class GFG {

static int maxSubArraySum(int a[], int size)
{
    int max_so_far = Integer.MIN_VALUE,
    max_ending_here = 0,start = 0,
    end = 0, s = 0;

    for (int i = 0; i < size; i++) 
    {
        max_ending_here += a[i];

        if (max_so_far < max_ending_here) 
        {
            max_so_far = max_ending_here;
            start = s;
            end = i;
        }

        if (max_ending_here < 0) 
        {
            max_ending_here = 0;
            s = i + 1;
        }
    }
    return (end - start + 1);
}

// Driver code
public static void main(String[] args)
{
    int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 };
    int n = a.length;
    System.out.println(maxSubArraySum(a, n));
}

}

Python3

Python3 program to print largest contiguous array sum

from sys import maxsize

Function to find the maximum contiguous subarray

and print its starting and end index

def maxSubArraySum(a,size):

max_so_far = -maxsize - 1
max_ending_here = 0
start = 0
end = 0
s = 0

for i in range(0,size):

    max_ending_here += a[i]

    if max_so_far < max_ending_here:
        max_so_far = max_ending_here
        start = s
        end = i

    if max_ending_here < 0:
        max_ending_here = 0
        s = i+1

return (end - start + 1)

Driver program to test maxSubArraySum

a = [-2, -3, 4, -1, -2, 1, 5, -3] print(maxSubArraySum(a,len(a)))

C#

// C# program to print length of the // largest contiguous array sum using System;

class GFG {

// Function to find maximum subarray sum
static int maxSubArraySum(int []a, int size)
{
    int max_so_far = int.MinValue,
    max_ending_here = 0,start = 0,
    end = 0, s = 0;

    for (int i = 0; i < size; i++) 
    {
        max_ending_here += a[i];

        if (max_so_far < max_ending_here) 
        {
            max_so_far = max_ending_here;
            start = s;
            end = i;
        }

        if (max_ending_here < 0) 
        {
            max_ending_here = 0;
            s = i + 1;
        }
    }
    return (end - start + 1);
}

// Driver code
public static void Main(String[] args)
{
    int []a = {-2, -3, 4, -1, -2, 1, 5, -3};
    int n = a.Length;
    Console.Write(maxSubArraySum(a, n));
}

}

// This code is contributed by parashar...

PHP

y1,y1, y1,x2, $y2) { mnew=2∗(m_new = 2 * (mnew=2(y2 - y1);<spanclass="katex"><spanclass="katex−mathml"><mathxmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>s</mi><mi>l</mi><mi>o</mi><mi>p</mi><msub><mi>e</mi><mi>e</mi></msub><mi>r</mi><mi>r</mi><mi>o</mi><msub><mi>r</mi><mi>n</mi></msub><mi>e</mi><mi>w</mi><mo>=</mo></mrow><annotationencoding="application/x−tex">slopeerrornew=</annotation></semantics></math></span><spanclass="katex−html"aria−hidden="true"><spanclass="base"><spanclass="strut"style="height:0.8889em;vertical−align:−0.1944em;"></span><spanclass="mordmathnormal">s</span><spanclass="mordmathnormal"style="margin−right:0.01968em;">l</span><spanclass="mordmathnormal">o</span><spanclass="mordmathnormal">p</span><spanclass="mord"><spanclass="mordmathnormal">e</span><spanclass="msupsub"><spanclass="vlist−tvlist−t2"><spanclass="vlist−r"><spanclass="vlist"style="height:0.1514em;"><spanstyle="top:−2.55em;margin−left:0em;margin−right:0.05em;"><spanclass="pstrut"style="height:2.7em;"></span><spanclass="sizingreset−size6size3mtight"><spanclass="mordmathnormalmtight">e</span></span></span></span><spanclass="vlist−s">​</span></span><spanclass="vlist−r"><spanclass="vlist"style="height:0.15em;"><span></span></span></span></span></span></span><spanclass="mordmathnormal">rro</span><spanclass="mord"><spanclass="mordmathnormal"style="margin−right:0.02778em;">r</span><spanclass="msupsub"><spanclass="vlist−tvlist−t2"><spanclass="vlist−r"><spanclass="vlist"style="height:0.1514em;"><spanstyle="top:−2.55em;margin−left:−0.0278em;margin−right:0.05em;"><spanclass="pstrut"style="height:2.7em;"></span><spanclass="sizingreset−size6size3mtight"><spanclass="mordmathnormalmtight">n</span></span></span></span><spanclass="vlist−s">​</span></span><spanclass="vlist−r"><spanclass="vlist"style="height:0.15em;"><span></span></span></span></span></span></span><spanclass="mordmathnormal">e</span><spanclass="mordmathnormal"style="margin−right:0.02691em;">w</span><spanclass="mspace"style="margin−right:0.2778em;"></span><spanclass="mrel">=</span></span></span></span>mnew−(y1); <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>s</mi><mi>l</mi><mi>o</mi><mi>p</mi><msub><mi>e</mi><mi>e</mi></msub><mi>r</mi><mi>r</mi><mi>o</mi><msub><mi>r</mi><mi>n</mi></msub><mi>e</mi><mi>w</mi><mo>=</mo></mrow><annotation encoding="application/x-tex">slope_error_new = </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord mathnormal">s</span><span class="mord mathnormal" style="margin-right:0.01968em;">l</span><span class="mord mathnormal">o</span><span class="mord mathnormal">p</span><span class="mord"><span class="mord mathnormal">e</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.1514em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight">e</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal">rro</span><span class="mord"><span class="mord mathnormal" style="margin-right:0.02778em;">r</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.1514em;"><span style="top:-2.55em;margin-left:-0.0278em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight">n</span></span></span></span><span class="vlist-s">​</span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal">e</span><span class="mord mathnormal" style="margin-right:0.02691em;">w</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span></span></span></span>m_new - (y1);<spanclass="katex"><spanclass="katexmathml"><mathxmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>s</mi><mi>l</mi><mi>o</mi><mi>p</mi><msub><mi>e</mi><mi>e</mi></msub><mi>r</mi><mi>r</mi><mi>o</mi><msub><mi>r</mi><mi>n</mi></msub><mi>e</mi><mi>w</mi><mo>=</mo></mrow><annotationencoding="application/xtex">slopeerrornew=</annotation></semantics></math></span><spanclass="katexhtml"ariahidden="true"><spanclass="base"><spanclass="strut"style="height:0.8889em;verticalalign:0.1944em;"></span><spanclass="mordmathnormal">s</span><spanclass="mordmathnormal"style="marginright:0.01968em;">l</span><spanclass="mordmathnormal">o</span><spanclass="mordmathnormal">p</span><spanclass="mord"><spanclass="mordmathnormal">e</span><spanclass="msupsub"><spanclass="vlisttvlistt2"><spanclass="vlistr"><spanclass="vlist"style="height:0.1514em;"><spanstyle="top:2.55em;marginleft:0em;marginright:0.05em;"><spanclass="pstrut"style="height:2.7em;"></span><spanclass="sizingresetsize6size3mtight"><spanclass="mordmathnormalmtight">e</span></span></span></span><spanclass="vlists"></span></span><spanclass="vlistr"><spanclass="vlist"style="height:0.15em;"><span></span></span></span></span></span></span><spanclass="mordmathnormal">rro</span><spanclass="mord"><spanclass="mordmathnormal"style="marginright:0.02778em;">r</span><spanclass="msupsub"><spanclass="vlisttvlistt2"><spanclass="vlistr"><spanclass="vlist"style="height:0.1514em;"><spanstyle="top:2.55em;marginleft:0.0278em;marginright:0.05em;"><spanclass="pstrut"style="height:2.7em;"></span><spanclass="sizingresetsize6size3mtight"><spanclass="mordmathnormalmtight">n</span></span></span></span><spanclass="vlists"></span></span><spanclass="vlistr"><spanclass="vlist"style="height:0.15em;"><span></span></span></span></span></span></span><spanclass="mordmathnormal">e</span><spanclass="mordmathnormal"style="marginright:0.02691em;">w</span><spanclass="mspace"style="marginright:0.2778em;"></span><spanclass="mrel">=</span></span></span></span>mnew(x2 - $x1); for ($x = x1,x1, x1,y = y1;y1; y1;x <= x2;x2; x2;x++) { echo "(" ,$x , "," , $y, ")\n"; // Add slope to increment // angle formed slopeerrornew+=slope_error_new += slopeerrornew+=m_new; // Slope error reached limit, // time to increment y and // update slope error. if ($slope_error_new >= 0) { $y++; slopeerrornew−=2∗(slope_error_new -= 2 * (slopeerrornew=2(x2 - $x1); } } } // Driver Code x1=3;x1 = 3; x1=3;y1 = 2; x2=15;x2 = 15; x2=15;y2 = 5; bresenham($x1, y1,y1, y1,x2, $y2); // This code is contributed by nitin mittal. ?>

JavaScript

`

Time Complexity: O(n)
Auxiliary Space: O(1)

Approach#2: Using Kadane's algorithm

This approach implements the Kadane's algorithm to find the maximum subarray sum and returns the size of the subarray with maximum sum.

Algorithm

1. Initialize max_sum, current_sum, start, end, max_start, and max_end to the first element of the array.
2. Iterate through the array from the second element.
3. If the current element is greater than the sum of the current element and current_sum, update start to the current index.
4. Update current_sum as the maximum of the current element and the sum of current element and current_sum.
5. If current_sum is greater than max_sum, update max_sum, end to the current index, and max_start and max_end to start and end respectively.
6. Return max_end - max_start + 1 as the size of the subarray with maximum sum.

C++ `

#include <bits/stdc++.h> using namespace std;

// Function to find the maximum subarray sum int max_subarray_sum(vector& a) { int n = a.size(); int max_sum = a[0]; int current_sum = a[0]; int start = 0; int end = 0; int max_start = 0; int max_end = 0;

// Traverse the array
for (int i = 1; i < n; i++) {
    // If the current element is greater than the sum so
    // far plus the current element, then update the
    // start index to the current index
    if (a[i] > current_sum + a[i]) {
        start = i;
    }

    // Update the current sum to be either the current
    // element or the sum so far plus the current
    // element
    current_sum = max(a[i], current_sum + a[i]);

    // If the current sum is greater than the maximum
    // sum so far, then update the maximum sum and its
    // start and end indices
    if (current_sum > max_sum) {
        max_sum = current_sum;
        end = i;
        max_start = start;
        max_end = end;
    }
}

// Return the length of the maximum subarray
return max_end - max_start + 1;

}

int main() { vector a{ -2, -3, 4, -1, -2, 1, 5, -3 }; cout << max_subarray_sum(a) << endl; return 0; }

Java

import java.util.*;

public class Main {

// Function to find the maximum subarray sum static int maxSubarraySum(List a) { int n = a.size(); int max_sum = a.get(0); int current_sum = a.get(0); int start = 0; int end = 0; int max_start = 0; int max_end = 0;

// Traverse the list
for (int i = 1; i < n; i++) {
  // If the current element is greater than the sum so
  // far plus the current element, then update the
  // start index to the current index
  if (a.get(i) > current_sum + a.get(i)) {
    start = i;
  }

  // Update the current sum to be either the current
  // element or the sum so far plus the current
  // element
  current_sum = Math.max(a.get(i), current_sum + a.get(i));

  // If the current sum is greater than the maximum
  // sum so far, then update the maximum sum and its
  // start and end indices
  if (current_sum > max_sum) {
    max_sum = current_sum;
    end = i;
    max_start = start;
    max_end = end;
  }
}

// Return the length of the maximum subarray
return max_end - max_start + 1;

}

public static void main(String[] args) { List a = Arrays.asList(-2, -3, 4, -1, -2, 1, 5, -3); System.out.println(maxSubarraySum(a)); } }

Python3

def max_subarray_sum(a): n = len(a) max_sum = a[0] current_sum = a[0] start = 0 end = 0 max_start = 0 max_end = 0

for i in range(1, n):
    if a[i] > current_sum + a[i]:
        start = i
    current_sum = max(a[i], current_sum + a[i])
    if current_sum > max_sum:
        max_sum = current_sum
        end = i
        max_start = start
        max_end = end

return max_end - max_start + 1

a = [-2, -3, 4, -1, -2, 1, 5, -3] print(max_subarray_sum(a))

C#

using System; using System.Collections.Generic;

public class MaxSubarraySum { public static int FindMaxSubarraySum(List a) { int n = a.Count; int maxSum = a[0]; int currentSum = a[0]; int start = 0; int end = 0; int maxStart = 0; int maxEnd = 0;

    // Traverse the list
    for (int i = 1; i < n; i++) {
        // If the current element is greater than the sum so
        // far plus the current element, then update the
        // start index to the current index
        if (a[i] > currentSum + a[i]) {
            start = i;
        }

        // Update the current sum to be either the current
        // element or the sum so far plus the current
        // element
        currentSum = Math.Max(a[i], currentSum + a[i]);

        // If the current sum is greater than the maximum
        // sum so far, then update the maximum sum and its
        // start and end indices
        if (currentSum > maxSum) {
            maxSum = currentSum;
            end = i;
            maxStart = start;
            maxEnd = end;
        }
    }

    // Return the length of the maximum subarray
    return maxEnd - maxStart + 1;
}

public static void Main() {
    List<int> a = new List<int> { -2, -3, 4, -1, -2, 1, 5, -3 };
    Console.WriteLine(FindMaxSubarraySum(a));
}

}

JavaScript

function max_subarray_sum(a) { const n = a.length; let max_sum = a[0]; let current_sum = a[0]; let start = 0; let end = 0; let max_start = 0; let max_end = 0;

// Traverse the array for (let i = 1; i < n; i++) { // If the current element is greater than the sum so // far plus the current element, then update the // start index to the current index if (a[i] > current_sum + a[i]) { start = i; }

// Update the current sum to be either the current
// element or the sum so far plus the current
// element
current_sum = Math.max(a[i], current_sum + a[i]);

// If the current sum is greater than the maximum
// sum so far, then update the maximum sum and its
// start and end indices
if (current_sum > max_sum) {
  max_sum = current_sum;
  end = i;
  max_start = start;
  max_end = end;
}

}

// Return the length of the maximum subarray return max_end - max_start + 1; }

const a = [-2, -3, 4, -1, -2, 1, 5, -3]; console.log(max_subarray_sum(a)); //This code is contributed by Zaidkhan15

`

Time Complexity: O(n), where n is length of array
Auxiliary Space: O(1)

Note: The above code assumes that there is at least one positive element in the array. If all the elements are negative, the code needs to be modified to return the maximum element in the array.