Skip to content

Commit

Permalink
Create Kadane'sAlgorithm.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
o10a19 authored and x0lg0n committed Nov 1, 2024
1 parent 57d3e6d commit 7dd31b1
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions C++/Kadane'sAlgorithm.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#include <iostream>
#include <vector>
using namespace std;

int kadane(const vector<int>& arr) {
int max_so_far = arr[0], max_ending_here = arr[0];

for (size_t i = 1; i < arr.size(); i++) {
max_ending_here = max(arr[i], max_ending_here + arr[i]);
max_so_far = max(max_so_far, max_ending_here);
}

return max_so_far;
}

int main() {
vector<int> arr = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
cout << "Maximum sum of contiguous subarray is: " << kadane(arr) << endl;
return 0;
}

0 comments on commit 7dd31b1

Please sign in to comment.