Print subarray with maximum sum (original) (raw)

Last Updated : 19 Aug, 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: _{7, -1, 2, 3}
**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.

Table of Content

**[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 maxSumSubarray(vector &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 arr = {2, 3, -8, 7, -1, 2, 3}; vector 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:

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 maxSumSubarray(vector &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 arr = {2, 3, -8, 7, -1, 2, 3}; vector 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)