[Hacker Rank] The Maximum Subarray

The Maximum Subarray

  • Time : O(n)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
vector<int> maxSubarray(vector<int> A) {
int subseq = 0, subarr = -1e8;
int kadane = 0;
for(auto& a : A) {
kadane = max(kadane + a, a);
subarr = max(subarr, kadane);
if(a > 0) subseq += a;
}

if(subseq == 0) subseq = *max_element(begin(A), end(A));
return {subarr, subseq};
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/15/PS/HackerRank/three-month-preparation-kit-maxsubarray/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.