Size of The Subarray With Maximum Sum
Last Updated :
11 Jul, 2025
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
<?php
// PHP program for Bresenham’s
// Line Generation Assumptions :
// 1) Line is drawn from
// left to right.
// 2) x1 < x2 and y1 < y2
// 3) Slope of the line is
// between 0 and 1.
// We draw a line from lower
// left to upper right.
// function for line generation
function bresenham($x1, $y1, $x2, $y2)
{
$m_new = 2 * ($y2 - $y1);
$slope_error_new = $m_new - ($x2 - $x1);
for ($x = $x1, $y = $y1; $x <= $x2; $x++)
{
echo "(" ,$x , "," , $y, ")\n";
// Add slope to increment
// angle formed
$slope_error_new += $m_new;
// Slope error reached limit,
// time to increment y and
// update slope error.
if ($slope_error_new >= 0)
{
$y++;
$slope_error_new -= 2 * ($x2 - $x1);
}
}
}
// Driver Code
$x1 = 3; $y1 = 2; $x2 = 15; $y2 = 5;
bresenham($x1, $y1, $x2, $y2);
// This code is contributed by nitin mittal.
?>
JavaScript
<script>
// JavaScript program to print length
// of the largest contiguous array sum
function maxSubArraySum(a, size)
{
let max_so_far = Number.MIN_VALUE,
max_ending_here = 0,start = 0,
end = 0, s = 0;
for(let 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
let a = [ -2, -3, 4, -1, -2, 1, 5, -3 ];
let n = a.length;
document.write(maxSubArraySum(a, n));
// This code is contributed by splevel62
</script>
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<int>& 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<int> 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<Integer> 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<Integer> 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<int> 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.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem