TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
kadane.cpp
Go to the documentation of this file.
1
20#include <array>
21#include <climits>
22#include <iostream>
27namespace dynamic_programming {
33namespace kadane {
41template <size_t N>
42int maxSubArray(const std::array<int, N> &n) {
43 int curr_sum =
44 0; // declaring a variable named as curr_sum and initialized it to 0
45 int max_sum = INT_MIN; // Initialized max_sum to INT_MIN
46 for (int i : n) { // for loop to iterate over the elements of the array
47 curr_sum += n[i];
48 max_sum = std::max(max_sum, curr_sum); // getting the maximum value
49 curr_sum = std::max(curr_sum, 0); // updating the value of curr_sum
50 }
51 return max_sum; // returning the value of max_sum
52}
53} // namespace kadane
54} // namespace dynamic_programming
55
60int main() {
61 const int N = 5;
62 std::array<int, N> n{}; // declaring array
63 // taking values of elements from user
64 for (int i = 0; i < n.size(); i++) {
65 std::cout << "Enter value of n[" << i << "]"
66 << "\n";
67 std::cin >> n[i];
68 }
69 int max_sum = dynamic_programming::kadane::maxSubArray<N>(
70 n); // calling maxSubArray function
71 std::cout << "Maximum subarray sum is " << max_sum; // Printing the answer
72
73 return 0;
74}
int main()
Main function.
Definition kadane.cpp:60
int maxSubArray(const std::array< int, N > &n)
maxSubArray function is used to calculate the maximum sum subarray and returns the value of maximum s...
Definition kadane.cpp:42
Dynamic Programming algorithms.
Functions for Kadane algorithm.