Size of The Subarray With Maximum Sum

Hello Everyone,

An array is given, find 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}.

The idea is to update starting index whenever sum ending here becomes less than 0.

  • C++
  • Java
  • Python3
  • C#
  • PHP
  • Javascript

// 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;

}

Output :

5

NOTE.

Subarray
A subarray is a contiguous part of array. An array that is inside another array. For example, consider the array [1, 2, 3, 4], There are 10 non-empty sub-arrays. The subarrays are (1), (2), (3), (4), (1,2), (2,3), (3,4), (1,2,3), (2,3,4) and (1,2,3,4). In general, for an array/string of size n, there are n(n+1)/2* non-empty subarrays/substrings.

Subsequence
A subsequence is a sequence that can be derived from another sequence by zero or more elements, without changing the order of the remaining elements.
For the same example, there are 15 sub-sequences. They are (1), (2), (3), (4), (1,2), (1,3),(1,4), (2,3), (2,4), (3,4), (1,2,3), (1,2,4), (1,3,4), (2,3,4), (1,2,3,4). More generally, we can say that for a sequence of size n, we can have (2n-1 ) non-empty sub-sequences in total.