Print subarray with maximum sum
Last Updated :
15 Jul, 2025
Given an array arr[], the task is to print the subarray having maximum sum.
Examples:
Input: arr[] = {2, 3, -8, 7, -1, 2, 3}
Output: 11
Explanation: The subarray {7, -1, 2, 3} has the largest sum 11.
Input: arr[] = {-2, -5, 6, -2, -3, 1, 5, -6}
Output: {6, -2, -3, 1, 5}
Explanation: The subarray {6, -2, -3, 1, 5} has the largest sum of 7.
[Naive Approach] By iterating over all subarrays - O(n^2) Time and O(1) Space
The idea is to run two nested loops to iterate over all possible subarrays and find the maximum sum. The outer loop will mark the starting point of a subarray and inner loop will mark the ending point of the subarray. At any time, if we find a subarray whose sum is greater than the maximum sum so far, then we will update the starting and ending point of the maximum sum subarray.
C++
// C++ Program to print subarray with maximum sum using nested loops
#include <bits/stdc++.h>
using namespace std;
// Function to find the subarray with maximum sum
vector<int> maxSumSubarray(vector<int> &arr) {
// start and end of max sum subarray
int resStart = 0, resEnd = 0;
// Initialize the maximum subarray sum with the first element
int maxSum = arr[0];
for (int i = 0; i < arr.size(); i++) {
// Initialize current subarray sum with 0
int currSum = 0;
for(int j = i; j < arr.size(); j++) {
currSum += arr[j];
// If current subarray has greater sum than maximum sum subarray,
// then update the start and end of maximum sum subarray
if(currSum > maxSum) {
maxSum = currSum;
resStart = i;
resEnd = j;
}
}
}
vector<int> res;
for(int i = resStart; i <= resEnd; i++)
res.push_back(arr[i]);
return res;
}
int main() {
vector<int> arr = {2, 3, -8, 7, -1, 2, 3};
vector<int> res = maxSumSubarray(arr);
for(int i = 0; i < res.size(); i++)
cout << res[i] << " ";
return 0;
}
Java
// Java Program to print subarray with maximum sum using nested loops
import java.util.ArrayList;
import java.util.List;
class GfG {
// Function to find the subarray with maximum sum
static List<Integer> maxSumSubarray(int[] arr) {
// start and end of max sum subarray
int resStart = 0, resEnd = 0;
// Initialize the maximum subarray sum with the first element
int maxSum = arr[0];
for (int i = 0; i < arr.length; i++) {
// Initialize current subarray sum with 0
int currSum = 0;
for (int j = i; j < arr.length; j++) {
currSum += arr[j];
// If current subarray has greater sum than maximum sum subarray,
// then update the start and end of maximum sum subarray
if (currSum > maxSum) {
maxSum = currSum;
resStart = i;
resEnd = j;
}
}
}
List<Integer> res = new ArrayList<>();
for (int i = resStart; i <= resEnd; i++)
res.add(arr[i]);
return res;
}
public static void main(String[] args) {
int[] arr = {2, 3, -8, 7, -1, 2, 3};
List<Integer> res = maxSumSubarray(arr);
for (int num : res)
System.out.print(num + " ");
System.out.println();
}
}
Python
# Python Program to print subarray with maximum sum using nested loops
# Function to find the subarray with maximum sum
def maxSumSubarray(arr):
# start and end of max sum subarray
resStart = 0
resEnd = 0
# Initialize the maximum subarray sum with the first element
maxSum = arr[0]
for i in range(len(arr)):
# Initialize current subarray sum with 0
currSum = 0
for j in range(i, len(arr)):
currSum += arr[j]
# If current subarray has greater sum than maximum sum subarray,
# then update the start and end of maximum sum subarray
if currSum > maxSum:
maxSum = currSum
resStart = i
resEnd = j
res = []
for i in range(resStart, resEnd + 1):
res.append(arr[i])
return res
arr = [2, 3, -8, 7, -1, 2, 3]
res = maxSumSubarray(arr)
for num in res:
print(num, end=" ")
print()
C#
// C# Program to print subarray with maximum sum using nested loops
using System;
using System.Collections.Generic;
class GfG {
// Function to find the subarray with maximum sum
static List<int> maxSumSubarray(int[] arr) {
// start and end of max sum subarray
int resStart = 0, resEnd = 0;
// Initialize the maximum subarray sum with the first element
int maxSum = arr[0];
for (int i = 0; i < arr.Length; i++) {
// Initialize current subarray sum with 0
int currSum = 0;
for (int j = i; j < arr.Length; j++) {
currSum += arr[j];
// If current subarray has greater sum than maximum sum subarray,
// then update the start and end of maximum sum subarray
if (currSum > maxSum) {
maxSum = currSum;
resStart = i;
resEnd = j;
}
}
}
List<int> res = new List<int>();
for (int i = resStart; i <= resEnd; i++)
res.Add(arr[i]);
return res;
}
static void Main() {
int[] arr = { 2, 3, -8, 7, -1, 2, 3 };
List<int> res = maxSumSubarray(arr);
foreach (int num in res)
Console.Write(num + " ");
Console.WriteLine();
}
}
JavaScript
// Function to find the subarray with maximum sum
function maxSumSubarray(arr) {
// start and end of max sum subarray
let resStart = 0, resEnd = 0;
// Initialize the maximum subarray sum with the first element
let maxSum = arr[0];
for (let i = 0; i < arr.length; i++) {
// Initialize current subarray sum with 0
let currSum = 0;
for (let j = i; j < arr.length; j++) {
currSum += arr[j];
// If current subarray has greater sum than maximum sum subarray,
// then update the start and end of maximum sum subarray
if (currSum > maxSum) {
maxSum = currSum;
resStart = i;
resEnd = j;
}
}
}
let res = [];
for (let i = resStart; i <= resEnd; i++)
res.push(arr[i]);
return res;
}
// Example usage
const arr = [2, 3, -8, 7, -1, 2, 3];
const res = maxSumSubarray(arr);
console.log(res.join(" "));
Time complexity: O(n2), as we are iterating over all possible subarrays.
Auxiliary Space: O(1)
[Expected Approach] Using Kadane's Algorithm - O(n) Time and O(1) Space
The idea is similar to Kadane's Algorithm with the only difference that here, we need to keep track of the start and end of the subarray with maximum sum, that is the result array. Iterate over the array keeping track of the start and end of current subarray and at any point, if the sum of current subarray becomes greater than the result array, update the result array with the current subarray.
For each element, we have two choices:
- Choice 1: Extend the maximum sum subarray ending at the previous element by adding the current element to it. In this case, the ending index of the current subarray increases by 1.
- Choice 2: Start a new subarray starting from the current element. In this case, the starting index of the current subarray updates to the current index.
If the maximum sum ending at an element becomes greater than the result array, we update the start and end of result subarray with the start and end of current subarray respectively.
C++
// C++ Program to print subarray with maximum sum using Kadane's Algorithm
#include <bits/stdc++.h>
using namespace std;
// Function to find the subarray with maximum sum
vector<int> maxSumSubarray(vector<int> &arr) {
// start and end of max sum subarray
int resStart = 0, resEnd = 0;
// start of current subarray
int currStart = 0;
int maxSum = arr[0];
int maxEnding = arr[0];
for (int i = 1; i < arr.size(); i++) {
// If starting a new subarray from the current element
// has greater sum than extending the previous subarray
if(maxEnding + arr[i] < arr[i]) {
// Update current subarray sum with current element
// and start of current subarray with current index
maxEnding = arr[i];
currStart = i;
}
else {
// Add current element to current subarray sum
maxEnding += arr[i];
}
// If current subarray sum is greater than maximum subarray sum
if(maxEnding > maxSum) {
// Update maximum subarray sum
maxSum = maxEnding;
// Update start and end of maximum sum subarray
resStart = currStart;
resEnd = i;
}
}
vector<int> res;
for(int i = resStart; i <= resEnd; i++)
res.push_back(arr[i]);
return res;
}
int main() {
vector<int> arr = {2, 3, -8, 7, -1, 2, 3};
vector<int> res = maxSumSubarray(arr);
for(int i = 0; i < res.size(); i++)
cout << res[i] << " ";
return 0;
}
C
// C Program to print subarray with maximum sum using Kadane's Algorithm
#include <stdio.h>
#include <limits.h>
// Function to find the subarray with maximum sum
void maxSumSubarray(int arr[], int size, int* start, int* end,
int* res, int* resSize) {
// start and end of max sum subarray
int resStart = 0, resEnd = 0;
// start of current subarray
int currStart = 0;
int maxSum = arr[0];
int maxEnding = arr[0];
for (int i = 1; i < size; i++) {
// If starting a new subarray from the current element
// has greater sum than extending the previous subarray
if (maxEnding + arr[i] < arr[i]) {
// Update current subarray sum with current element
// and start of current subarray with current index
maxEnding = arr[i];
currStart = i;
}
else {
// Add current element to current subarray sum
maxEnding += arr[i];
}
// If current subarray sum is greater than maximum subarray sum
if (maxEnding > maxSum) {
// Update maximum subarray sum
maxSum = maxEnding;
// Update start and end of maximum sum subarray
resStart = currStart;
resEnd = i;
}
}
*start = resStart;
*end = resEnd;
*resSize = resEnd - resStart + 1;
for (int i = 0; i < *resSize; i++) {
res[i] = arr[resStart + i];
}
}
int main() {
int arr[] = {2, 3, -8, 7, -1, 2, 3};
int size = sizeof(arr) / sizeof(arr[0]);
int start, end, resSize;
int res[size];
maxSumSubarray(arr, size, &start, &end, res, &resSize);
for (int i = 0; i < resSize; i++) {
printf("%d ", res[i]);
}
return 0;
}
Java
// Java Program to print subarray with maximum sum using Kadane's Algorithm
import java.util.ArrayList;
import java.util.List;
class GfG {
// Function to find the sum of contiguous subarray with maximum sum
static List<Integer> maxSumSubarray(int[] arr) {
// start and end of max sum subarray
int resStart = 0, resEnd = 0;
// start of current subarray
int currStart = 0;
int maxSum = arr[0];
int maxEnding = arr[0];
for (int i = 1; i < arr.length; i++) {
// If starting a new subarray from the current element
// has greater sum than extending the previous subarray
if (maxEnding + arr[i] < arr[i]) {
// Update current subarray sum with current element
// and start of current subarray with current index
maxEnding = arr[i];
currStart = i;
}
else {
// Add current element to current subarray sum
maxEnding += arr[i];
}
// If current subarray sum is greater than maximum subarray sum
if (maxEnding > maxSum) {
// Update maximum subarray sum
maxSum = maxEnding;
// Update start and end of maximum sum subarray
resStart = currStart;
resEnd = i;
}
}
List<Integer> res = new ArrayList<>();
for (int i = resStart; i <= resEnd; i++)
res.add(arr[i]);
return res;
}
public static void main(String[] args) {
int[] arr = {2, 3, -8, 7, -1, 2, 3};
List<Integer> res = maxSumSubarray(arr);
for (int i = 0; i < res.size(); i++)
System.out.print(res.get(i) + " ");
}
}
Python
# Python Program to print subarray with maximum sum using Kadane's Algorithm
# Function to find the subarray with maximum sum
def maxSumSubarray(arr):
# start and end of max sum subarray
resStart = 0
resEnd = 0
# start of current subarray
currStart = 0
maxSum = arr[0]
maxEnding = arr[0]
for i in range(1, len(arr)):
# If starting a new subarray from the current element
# has greater sum than extending the previous subarray
if maxEnding + arr[i] < arr[i]:
# Update current subarray sum with current element
# and start of current subarray with current index
maxEnding = arr[i]
currStart = i
else:
# Add current element to current subarray sum
maxEnding += arr[i]
# If current subarray sum is greater than maximum subarray sum
if maxEnding > maxSum:
# Update maximum subarray sum
maxSum = maxEnding
# Update start and end of maximum sum subarray
resStart = currStart
resEnd = i
res = arr[resStart:resEnd + 1]
return res
if __name__ == "__main__":
arr = [2, 3, -8, 7, -1, 2, 3]
res = maxSumSubarray(arr)
for num in res:
print(num, end=" ")
C#
// C# Program to print subarray with maximum sum using Kadane's Algorithm
using System;
using System.Collections.Generic;
class GfG {
// Function to find the subarray with maximum sum
static List<int> MaxSumSubarray(List<int> arr) {
// start and end of max sum subarray
int resStart = 0, resEnd = 0;
// start of current subarray
int currStart = 0;
int maxSum = arr[0];
int maxEnding = arr[0];
for (int i = 1; i < arr.Count; i++) {
// If starting a new subarray from the current element
// has greater sum than extending the previous subarray
if (maxEnding + arr[i] < arr[i]) {
// Update current subarray sum with current element
// and start of current subarray with current index
maxEnding = arr[i];
currStart = i;
}
else {
// Add current element to current subarray sum
maxEnding += arr[i];
}
// If current subarray sum is greater than maximum subarray sum
if (maxEnding > maxSum) {
// Update maximum subarray sum
maxSum = maxEnding;
// Update start and end of maximum sum subarray
resStart = currStart;
resEnd = i;
}
}
List<int> res = new List<int>();
for (int i = resStart; i <= resEnd; i++)
res.Add(arr[i]);
return res;
}
static void Main() {
List<int> arr = new List<int> { 2, 3, -8, 7, -1, 2, 3 };
List<int> res = MaxSumSubarray(arr);
for (int i = 0; i < res.Count; i++) {
Console.Write(res[i] + " ");
}
}
}
JavaScript
// JavaScript Program to print subarray with maximum sum using Kadane's Algorithm
// Function to find the subarray with maximum sum
function maxSumSubarray(arr) {
// start and end of max sum subarray
let resStart = 0, resEnd = 0;
// start of current subarray
let currStart = 0;
let maxSum = arr[0];
let maxEnding = arr[0];
for (let i = 1; i < arr.length; i++) {
// If starting a new subarray from the current element
// has greater sum than extending the previous subarray
if (maxEnding + arr[i] < arr[i]) {
// Update current subarray sum with current element
// and start of current subarray with current index
maxEnding = arr[i];
currStart = i;
} else {
// Add current element to current subarray sum
maxEnding += arr[i];
}
// If current subarray sum is greater than maximum subarray sum
if (maxEnding > maxSum) {
// Update maximum subarray sum
maxSum = maxEnding;
// Update start and end of maximum sum subarray
resStart = currStart;
resEnd = i;
}
}
let res = [];
for (let i = resStart; i <= resEnd; i++) {
res.push(arr[i]);
}
return res;
}
let arr = [2, 3, -8, 7, -1, 2, 3];
let res = maxSumSubarray(arr);
console.log(res.join(" "));
Time Complexity: O(n), as we are traversing the array only once.
Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Getting Started with Array Data StructureArray is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
14 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