TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
maximum_circular_subarray.cpp
Go to the documentation of this file.
1
10#include <cassert>
11#include <iostream>
12#include <vector>
13
14
19namespace dynamic_programming {
26int maxCircularSum(std::vector<int>& arr)
27{
28 // Edge Case
29 if (arr.size() == 1)
30 return arr[0];
31
32 // Sum variable which stores total sum of the array.
33 int sum = 0;
34 for (int i = 0; i < arr.size(); i++) {
35 sum += arr[i];
36 }
37
38 // Every variable stores first value of the array.
39 int current_max = arr[0], max_so_far = arr[0], current_min = arr[0], min_so_far = arr[0];
40
41 // Concept of Kadane's Algorithm
42 for (int i = 1; i < arr.size(); i++) {
43 // Kadane's Algorithm to find Maximum subarray sum.
44 current_max = std::max(current_max + arr[i], arr[i]);
45 max_so_far = std::max(max_so_far, current_max);
46
47 // Kadane's Algorithm to find Minimum subarray sum.
48 current_min = std::min(current_min + arr[i], arr[i]);
49 min_so_far = std::min(min_so_far, current_min);
50 }
51
52 if (min_so_far == sum)
53 return max_so_far;
54
55 // Return the maximum value
56 return std::max(max_so_far, sum - min_so_far);
57}
58} // namespace dynamic_programming
59
64static void test() {
65 // Description of the test
66 // Input: arr[] = {8, -8, 9, -9, 10, -11, 12}
67 // Output: 22
68 // Explanation: Subarray 12, 8, -8, 9, -9, 10 gives the maximum sum, that is 22.
69
70 int n = 7; // size of the array
71 std::vector<int> arr = {8, -8, 9, -9, 10, -11, 12};
72 assert(dynamic_programming::maxCircularSum(arr) == 22); // this ensures that the algorithm works as expected
73
74 arr = {8, -8, 10, -9, 10, -11, 12};
75 assert(dynamic_programming::maxCircularSum(arr) == 23);
76
77 std::cout << "All tests have successfully passed!\n";
78}
79
80
87int main(int argc, char *argv[]) {
88 test(); // run self-test implementations
89 return 0;
90}
int main()
Main function.
static void test()
Self-test implementation.
Dynamic Programming algorithms.
int maxCircularSum(std::vector< int > &arr)
returns the maximum contiguous circular sum of an array