[Geeks for Geeks] Kadane`s Algorithm

Kadane’s Algorithm

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

  • Time : O(n)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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){
long long res = arr[0], sum = 0;
for(int i = 0; i < n; i++) {
sum = max(sum + arr[i], (long long)arr[i]);
res = max(res, sum);
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/20/PS/GeeksforGeeks/kadanes-algorithm/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.