forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Max_subarray_sum_constant_space(DP).cpp
70 lines (49 loc) · 1.62 KB
/
Max_subarray_sum_constant_space(DP).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
66
67
68
69
70
/*
We can easily solve this problem in linear time using kadane’s algorithm.
The idea is to maintain maximum (positive sum) sub-array “ending” at each index of the given array.
This subarray is either empty (in which case its sum is zero) or consists of one more element than the maximum subarray ending at the previous index.
And, To Cover Both Positive and Negative Cases, approach requires two traversals of the input array.
*/
#include <bits/stdc++.h>
#define ll long long int
using namespace std;
// Function to find contiguous sub-array with the largest sum
// in given set of integers (handles negative numbers as well)
int kadane(ll arr[], ll n)
{
// stores maximum sum sub-array found so far
ll max_so_far = arr[0];
// stores maximum sum of sub-array ending at current position
ll max_ending_here = arr[0];
for (ll i = 1; i < n; i++)
{
// update maximum sum of sub-array "ending" at index i (by adding current element to maximum sum ending at previous index i-1)
max_ending_here = max_ending_here + arr[i];
// maximum sum is should be more than the current element
max_ending_here = max(max_ending_here, arr[i]);
// update result if current sub-array sum is found to be greater
max_so_far = max(max_so_far, max_ending_here);
}
return max_so_far;
}
int main()
{
ll n;
cin >> n;
ll arr[n];
for (ll i = 0; i < n; i++)
{
cin >> arr[i];
}
cout << "" << kadane(arr, n);
return 0;
}
/*
Time Complexity : O(n)
Space Complexity: O(1)
Sample Input:
8
-2 1 -3 4 -1 2 1 -5 4
Sample Output:
6
*/