From e2d878053da0c9c18f9f06593e97692ca7de68a7 Mon Sep 17 00:00:00 2001 From: Akhilesh Singh Bhadauriya <74489799+absolute-looser@users.noreply.github.com> Date: Wed, 20 Oct 2021 21:57:49 +0530 Subject: [PATCH] Created Kadane_algo.cpp Kadane algorithm is a standard algorithm that tells you the maximum that you can get from the addition of contiguous elements of the arrayy. --- Kadane_algo.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Kadane_algo.cpp diff --git a/Kadane_algo.cpp b/Kadane_algo.cpp new file mode 100644 index 0000000..3a011a3 --- /dev/null +++ b/Kadane_algo.cpp @@ -0,0 +1,25 @@ +#include +using namespace std; +// kadane's algorithm tells you about the longest contiguous subarray with maximum sum. +long long kadane(vector arr){ + long long ans = -1e18; + long long max = 0; + for(auto i:arr){ + max = max+i; + if(max>ans){ + ans = max; + }if(max<0){ + max = 0; + } + } + return ans; +} +int main(){ + int n; + cin >> n; + vector v(n); + for(auto &i:v){ + cin >> i; + } + cout << kadane(v) << endl; +}