Kadane's Algorithm

Kadane's Algorithm

Given an array of N integers. Find the contiguous sub-array(containing at least one number) which has the maximum sum and return its sum.

Example 1:

Input: N = 5 Arr[] = {1,2,3,-2,5} Output: 9 Explanation: Max subarray sum is 9 of elements (1, 2, 3, -2, 5) which is a contiguous subarray. Example 2:

Input: N = 4 Arr[] = {-1,-2,-3,-4} Output: -1 Explanation: Max subarray sum is -1 of element (-1)

In this using kadane's algo we can find longest contigious subarray we have to keep track of 2 varables current maximum and the max so far and we will update max so far as we traverse the array with max of current maximum.


#include<bits/stdc++.h>
using namespace std;
class Solution{
    public:
    // arr: input array
    // n: size of array
    //Function to find the sum of contiguous subarray with maximum sum.
    long long maxSubarraySum(int arr[], int n){

        // Your code here
        long long cs=arr[0],ms=arr[0],a;
        for(int i=1;i<n;i++)
        {
            a=arr[i];
            cs=max(cs+a,a);
            ms=max(ms,cs);
        }

        return ms;
    }
};

int main()
{
    int t,n;

    cin>>t; //input testcases
    while(t--) 
    {

        cin>>n; 

        int a[n];

        for(int i=0;i<n;i++)
            cin>>a[i]; 

        Solution ob;

        cout << ob.maxSubarraySum(a, n) << endl;
    }
}