forked from VinayBelwal/Hactober-22-Programs-and-Projects-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
MaximumSubarray.cpp
65 lines (52 loc) · 1.34 KB
/
MaximumSubarray.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// 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 elements
// 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;
}