# Print the Maximum Subarray Sum

Given an array arr[], the task is to find the elements of a contiguous subarray of numbers which has the largest sum.

Examples:

Input: arr = [-2, -3, 4, -1, -2, 1, 5, -3]
Output: [4, -1, -2, 1, 5]
Explanation:
In the above input the maximum contiguous subarray sum is 7 and the elements of the subarray are [4, -1, -2, 1, 5]

Input: arr = [-2, -5, 6, -2, -3, 1, 5, -6]
Output: [6, -2, -3, 1, 5]
Explanation:
In the above input the maximum contiguous subarray sum is 7 and the elements
of the subarray are [6, -2, -3, 1, 5]

Naive Approach: The naive approach is to generate all the possible subarray and print that subarray which has maximum sum.
Time complexity: O(N2
Auxiliary Space: O(1)
Efficient Approach: The idea is to use the Kadane’s Algorithm to find the maximum subarray sum and store the starting and ending index of the subarray having maximum sum and print the subarray from starting index to ending index. Below are the steps:

1. Initialize 3 variables endIndex to 0, currMax and globalMax to first value of the input array.
2. For each element in the array starting from index(say i) 1, update currMax to max(nums[i], nums[i] + currMax) and globalMax and endIndex to i only if currMax > globalMax.
3. To find the start index, iterate from endIndex in the left direction and keep decrementing the value of globalMax until it becomes 0. The point at which it becomes 0 is the start index.
4. Now print the subarray between [start, end].

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach` `#include ` `using` `namespace` `std;`   `// Function to print the elements` `// of Subarray with maximum sum` `void` `SubarrayWithMaxSum(vector<``int``>& nums)` `{` `    ``// Initialize currMax and globalMax` `    ``// with first value of nums` `    ``int` `endIndex, currMax = nums;` `    ``int` `globalMax = nums;`   `    ``// Iterate for all the elemensts` `    ``// of the array` `    ``for` `(``int` `i = 1; i < nums.size(); ++i) {`   `        ``// Update currMax` `        ``currMax = max(nums[i],` `                      ``nums[i] + currMax);`   `        ``// Check if currMax is greater` `        ``// than globalMax` `        ``if` `(currMax > globalMax) {` `            ``globalMax = currMax;` `            ``endIndex = i;` `        ``}` `    ``}`   `    ``int` `startIndex = endIndex;`   `    ``// Traverse in left direction to` `    ``// find start Index of subarray` `    ``while` `(startIndex >= 0) {`   `        ``globalMax -= nums[startIndex];`   `        ``if` `(globalMax == 0)` `            ``break``;`   `        ``// Decrement the start index` `        ``startIndex--;` `    ``}`   `    ``// Printing the elements of` `    ``// subarray with max sum` `    ``for` `(``int` `i = startIndex;` `         ``i <= endIndex; ++i) {`   `        ``cout << nums[i] << ``" "``;` `    ``}` `}`   `// Driver Code` `int` `main()` `{` `    ``// Given array arr[]` `    ``vector<``int``> arr` `        ``= { -2, -5, 6, -2,` `            ``-3, 1, 5, -6 };`   `    ``// Function call` `    ``SubarrayWithMaxSum(arr);` `    ``return` `0;` `}`

## Java

 `// Java program for the above approach` `import` `java.util.*;` `class` `GFG{`   `  ``// Function to print the elements` `  ``// of Subarray with maximum sum` `  ``static` `void` `SubarrayWithMaxSum(Vector nums)` `  ``{` `    ``// Initialize currMax and globalMax` `    ``// with first value of nums` `    ``int` `endIndex = ``0``, currMax = nums.get(``0``);` `    ``int` `globalMax = nums.get(``0``);`   `    ``// Iterate for all the elemensts` `    ``// of the array` `    ``for` `(``int` `i = ``1``; i < nums.size(); ++i)` `    ``{`   `      ``// Update currMax` `      ``currMax = Math.max(nums.get(i),` `                         ``nums.get(i) + currMax);`   `      ``// Check if currMax is greater` `      ``// than globalMax` `      ``if` `(currMax > globalMax) ` `      ``{` `        ``globalMax = currMax;` `        ``endIndex = i;` `      ``}` `    ``}`   `    ``int` `startIndex = endIndex;`   `    ``// Traverse in left direction to` `    ``// find start Index of subarray` `    ``while` `(startIndex >= ``0``) ` `    ``{` `      ``globalMax -= nums.get(startIndex);`   `      ``if` `(globalMax == ``0``)` `        ``break``;`   `      ``// Decrement the start index` `      ``startIndex--;` `    ``}`   `    ``// Printing the elements of` `    ``// subarray with max sum` `    ``for``(``int` `i = startIndex; i <= endIndex; ++i)` `    ``{` `      ``System.out.print(nums.get(i) + ``" "``);` `    ``}` `  ``}`   `  ``// Driver Code` `  ``public` `static` `void` `main(String[] args)` `  ``{` `    ``// Given array arr[]` `    ``Vector arr = ``new` `Vector();` `    ``arr.add(-``2``);` `    ``arr.add(-``5``);` `    ``arr.add(``6``);` `    ``arr.add(-``2``);` `    ``arr.add(-``3``);` `    ``arr.add(``1``);` `    ``arr.add(``5``);` `    ``arr.add(-``6``);`   `    ``// Function call` `    ``SubarrayWithMaxSum(arr);` `  ``}` `}`   `// This code is contributed by Rajput-Ji`

## C#

 `// C# program for the above approach` `using` `System;` `using` `System.Collections.Generic;` `class` `GFG{`   `  ``// Function to print the elements` `  ``// of Subarray with maximum sum` `  ``static` `void` `SubarrayWithMaxSum(List<``int``> nums)` `  ``{` `    ``// Initialize currMax and globalMax` `    ``// with first value of nums` `    ``int` `endIndex = 0, currMax = nums;` `    ``int` `globalMax = nums;`   `    ``// Iterate for all the elemensts` `    ``// of the array` `    ``for` `(``int` `i = 1; i < nums.Count; ++i)` `    ``{`   `      ``// Update currMax` `      ``currMax = Math.Max(nums[i],` `                         ``nums[i] + currMax);`   `      ``// Check if currMax is greater` `      ``// than globalMax` `      ``if` `(currMax > globalMax) ` `      ``{` `        ``globalMax = currMax;` `        ``endIndex = i;` `      ``}` `    ``}`   `    ``int` `startIndex = endIndex;`   `    ``// Traverse in left direction to` `    ``// find start Index of subarray` `    ``while` `(startIndex >= 0) ` `    ``{` `      ``globalMax -= nums[startIndex];`   `      ``if` `(globalMax == 0)` `        ``break``;`   `      ``// Decrement the start index` `      ``startIndex--;` `    ``}`   `    ``// Printing the elements of` `    ``// subarray with max sum` `    ``for``(``int` `i = startIndex; i <= endIndex; ++i)` `    ``{` `      ``Console.Write(nums[i] + ``" "``);` `    ``}` `  ``}`   `  ``// Driver Code` `  ``public` `static` `void` `Main(String[] args)` `  ``{` `    ``// Given array []arr` `    ``List<``int``> arr = ``new` `List<``int``>();` `    ``arr.Add(-2);` `    ``arr.Add(-5);` `    ``arr.Add(6);` `    ``arr.Add(-2);` `    ``arr.Add(-3);` `    ``arr.Add(1);` `    ``arr.Add(5);` `    ``arr.Add(-6);`   `    ``// Function call` `    ``SubarrayWithMaxSum(arr);` `  ``}` `}`   `// This code is contributed by gauravrajput1`

Output:

```6 -2 -3 1 5

```

Time complexity: O(N)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Improved By : Rajput-Ji, GauravRajput1