forked from ProAlgos/ProAlgos-Cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
kadane.hpp
67 lines (53 loc) · 1.54 KB
/
kadane.hpp
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
/*
Kadane's Algorithm
------------------
Used for finding the contiguous subarray within a one-dimensional array
of integers which has the largest sum.
Time complexity
---------------
O(N), where N is the number of elements in the original array.
Space complexity
----------------
O(1)
*/
#ifndef KADANE_HPP
#define KADANE_HPP
#include <tuple>
#include <vector>
using std::tuple;
using std::make_tuple;
using std::vector;
/*
maximum_subarray
---------------
Takes an array of integers as an argument and computes the maximum sum that
can be computed from any (contiguous) subarray of that array. Uses Kadane's
Algorithm, which employs dynamic programming.
Return value
------------
tuple<int, size_t, size_t>, in which int is the maximum subarray value and
size_t to size_t represents the indices of the passed subarray that sum to
that value.
*/
#define kadane maximum_subarray
tuple<int, size_t, size_t> maximum_subarray(const vector<int> &values)
{
int maxSum, currentSum;
size_t nextStart, start, end;
maxSum = currentSum = values[0];
nextStart = start = end = 0;
for (size_t i = 1; i < values.size(); i++) {
currentSum += values[i];
if (currentSum < values[i]) {
currentSum = values[i];
nextStart = i;
}
if (currentSum > maxSum) {
maxSum = currentSum;
start = nextStart;
end = i;
}
}
return make_tuple(maxSum, start, end);
}
#endif // KADANE_HPP