[Hacker Rank] Maximum Subarray Sum

Maximum Subarray Sum

  • Time : O(nlogn)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
long maximumSum(vector<long> a, long mod) {
long n = a.size(), res = 0;
set<long> s;
for(long i = 0, sum = 0; i < n; i++) {
sum = (sum + a[i]) % mod;
auto ub = s.upper_bound(sum);
if(ub == end(s)) {
res = max(res, sum);
} else {
res = max(res, mod - (*ub - sum));
}
s.insert(sum);
}
return res;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/11/PS/HackerRank/maximum-subarray-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.