-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3_LargestContinuousSum.cpp
78 lines (66 loc) · 2.38 KB
/
3_LargestContinuousSum.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
71
72
73
74
75
76
77
78
/**
Given an array of integers (positive and negative) find the largest continuous sum.
*/
#include <iostream>
#include <vector>
int32_t LargestContinuousSum(const std::vector<int>& integerArray) {
if(integerArray.size() == 0) {
return 0;
}
int32_t largestSum{0};
int32_t currentSum{0};
const auto updateResult = [&largestSum, ¤tSum](){
if(currentSum > largestSum) {
largestSum = currentSum;
currentSum = 0;
}};
for(const auto integer : integerArray) {
int32_t temp = currentSum + integer;
if(temp > currentSum) {
currentSum = temp;
// Corner case where we are at the last element of the array
if(integer == integerArray.back()) {
updateResult();
}
}
else{
updateResult();
}
}
return largestSum;
}
int main() {
{
const std::vector<int> testArray{1,-2,5,-1,2};
std::cout << "Expected Result: 5" << '\n' << "Actual Result: " << LargestContinuousSum(testArray) << '\n';
}
{
const std::vector<int> testArray{5, -1, -2, 3, -2};
std::cout << "Expected Result: 5" << '\n' << "Actual Result: " << LargestContinuousSum(testArray) << '\n';
}
{
const std::vector<int> testArray{ 5, 7, -13, 10, 5 };
std::cout << "Expected Result: 15" << '\n' << "Actual Result: " << LargestContinuousSum(testArray) << '\n';
}
{
const std::vector<int> testArray{0};
std::cout << "Expected Result: 0" << '\n' << "Actual Result: " << LargestContinuousSum(testArray) << '\n';
}
{
const std::vector<int> testArray{999999999};
std::cout << "Expected Result: 999999999" << '\n' << "Actual Result: " << LargestContinuousSum(testArray) << '\n';
}
{
const std::vector<int> testArray{-40,1,40,-50,1,50,-20,1,20,0,0};
std::cout << "Expected Result: 51" << '\n' << "Actual Result: " << LargestContinuousSum(testArray) << '\n';
}
{
const std::vector<int> testArray{2,-2,5,-5,6,-6};
std::cout << "Expected Result: 6" << '\n' << "Actual Result: " << LargestContinuousSum(testArray) << '\n';
}
{
const std::vector<int> testArray{1,-2,5,-1,6};
std::cout << "Expected Result: 6" << '\n' << "Actual Result: " << LargestContinuousSum(testArray) << '\n';
}
return 0;
}