Skip to content

Commit 1ce36d8

Browse files
authored
Create maximum-absolute-sum-of-any-subarray.cpp
1 parent 1df529b commit 1ce36d8

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
int maxAbsoluteSum(vector<int>& nums) {
7+
int curr = 0, mx = 0, mn = 0;
8+
for (const auto& num : nums) {
9+
curr += num;
10+
mx = max(mx, curr);
11+
mn = min(mn, curr);
12+
}
13+
return mx - mn;
14+
}
15+
};
16+
17+
// Time: O(n)
18+
// Space: O(1)
19+
class Solution2 {
20+
public:
21+
int maxAbsoluteSum(vector<int>& nums) {
22+
partial_sum(begin(nums), end(nums), begin(nums));
23+
return max(*max_element(cbegin(nums), cend(nums)), 0) -
24+
min(*min_element(cbegin(nums), cend(nums)), 0);
25+
}
26+
};

0 commit comments

Comments
 (0)