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:
Below is the implementation of the above approach:
// C++ program for the above approach
#include <bits/stdc++.h>
**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[0];
**int**
globalMax = nums[0];
// 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;
}
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.
#arrays #dynamic programming #algorithms-dynamic programming #kadane #subarray #subarray-sum