TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
kadanes3.cpp
Go to the documentation of this file.
1
17#include <array>
18#include <cassert>
19#include <climits>
20#include <cstdint>
21#include <iostream>
28template <std::size_t SIZE>
29int max_subarray_sum(std::array<int64_t, SIZE> arr, uint64_t length) {
30 int64_t current_max = INT_MIN, current_sum = 0;
31 for (int i = 0; i < length; i++) {
32 current_sum = current_sum + arr[i];
33 if (current_max < current_sum) {
34 current_max = current_sum;
35 }
36
37 if (current_sum < 0) {
38 current_sum = 0;
39 }
40 }
41 return current_max;
42}
43
48static void test() {
49 std::array<int64_t, 4> arr = {1, 2, 3, 4};
50 std::array<int64_t, 5> arr1 = {-1, -2, -4, -6, 7};
51 assert(max_subarray_sum(arr, 4) == 10);
52 assert(max_subarray_sum(arr1, 5) == 7);
53 std::cout << "All test cases have passed!\n";
54}
55
60int main() {
61 // Below is the code for accepting array from the user and then
62 // calling the function for the required output.
63 // It has been commented for now so that the test() function can run
64 // and the test cases can be verified.
65 // code for accepting array from user starts
66
67 // std::size_t n; // variable for length of input array
68 // std::cout << "Enter length of the array: ";
69 // std::cin >> n;
70 // std::array<int64_t, 100> arr = {0};
71 // // we need to give a constant in size. Hence we have allocated 100
72 // for now.
73 // for (int i = 0; i < n; i++)
74 // taking input of each element of the array
75 // {
76 // std::cin >> arr[i];
77 // }
78 // code for accepting array from user ends
79
80 // int max_sum = max_subarray_sum(arr, n);
81 // std::cout << "Maximum contiguous sum for this array is : " << max_sum
82 // << std::endl;
83
84 test(); // run self-test implementations
85 return 0;
86}
int max_subarray_sum(std::array< int64_t, SIZE > arr, uint64_t length)
for IO operations
Definition kadanes3.cpp:29
static void test()
Self-test implementations.
Definition kadanes3.cpp:48
int main()
Main function.
Definition kadanes3.cpp:60