Print subarray with maximum sum
Last Updated : 11 Sep, 2024
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
Size of The Subarray With Maximum Sum
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, -
10 min read
Longest Subarray with 0 Sum
Given an array arr[] of size n, the task is to find the length of the longest subarray with sum equal to 0. Examples: Input: arr[] = {15, -2, 2, -8, 1, 7, 10, 23}Output: 5Explanation: The longest subarray with sum equals to 0 is {-2, 2, -8, 1, 7} Input: arr[] = {1, 2, 3}Output: 0Explanation: There i
10 min read
Minimize the maximum subarray sum with 1s and -2s
Given two integers X and Y. X and Y represent the frequency of elements 1 and -2 you have. You have to arrange all elements such that the maximum sum over all subarrays is minimized, and then find the maximum subarray sum of such rearrangement. Examples: Input: X = 1, Y = 1Output: 1Explanation: X =
5 min read
Number of pairs with maximum sum
Given an array arr[], count number of pairs arr[i], arr[j] such that arr[i] + arr[j] is maximum and i < j. Example : Input : arr[] = {1, 1, 1, 2, 2, 2} Output : 3 Explanation: The maximum possible pair sum where i<j is 4, which is given by 3 pairs, so the answer is 3 the pairs are (2, 2), (2,
11 min read
CSES Solutions - Maximum Subarray Sum
Given an array arr[] of N integers, your task is to find the maximum sum of values in a contiguous, nonempty subarray. Examples: Input: N = 8, arr[] = {-1, 3, -2, 5, 3, -5, 2, 2}Output: 9Explanation: The subarray with maximum sum is {3, -2, 5, 3} with sum = 3 - 2 + 5 + 3 = 9. Input: N = 6, arr[] = {
5 min read
Maximum subarray sum modulo m
Given an array of n elements and an integer m. The task is to find the maximum value of the sum of its subarray modulo m i.e find the sum of each subarray mod m and print the maximum value of this modulo operation. Examples: Input: arr[] = {10, 7, 18}, m = 13Output: 12Explanation: All subarrays and
7 min read
Maximum Subarray Sum of Alternate Parity
Given array A[] of size N. The Task for this problem is to find the maximum subarray (Subarrays are arrays within another array. Subarrays contain contiguous elements) sum such that adjacent elements of the subarray should have different parity. Examples: Input: A[] = {-1, 4, -1, 0, 5, -4} Output: 8
7 min read
Maximum subarray sum in O(n) using prefix sum
Given an Array of Positive and Negative Integers, find out the Maximum Subarray Sum in that Array. Examples: Input1 : arr = {-2, -3, 4, -1, -2, 1, 5, -3} Output1 : 7 Input2 : arr = {4, -8, 9, -4, 1, -8, -1, 6} Output2 : 9 Kadane's Algorithm solves this problem using Dynamic Programming approach in l
8 min read
Maximum sum bitonic subarray
Given an array containing n numbers. The problem is to find the maximum sum bitonic subarray. A bitonic subarray is a subarray in which elements are first increasing and then decreasing. A strictly increasing or strictly decreasing subarray is also considered a bitonic subarray. Time Complexity of O
15+ min read
CSES Solutions - Maximum Subarray Sum II
Given an array arr[] of N integers, your task is to find the maximum sum of values in a contiguous subarray with length between A and B. Examples: Input: N = 8, A = 1, B = 2, arr[] = {-1, 3, -2, 5, 3, -5, 2, 2}Output: 8Explanation: The subarray with maximum sum is {5, 3}, the length between 1 and 2,
12 min read