Skip to content

Commit 7b3c17b

Browse files
authored
Create maximum-alternating-subarray-sum.cpp
1 parent b304b0a commit 7b3c17b

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
long long maximumAlternatingSubarraySum(vector<int>& nums) {
7+
return max(kadane(nums, 0), kadane(nums, 1));
8+
}
9+
10+
private:
11+
int64_t kadane(const vector<int>& nums, int start) {
12+
int64_t result = numeric_limits<int64_t>::min();
13+
for (int64_t i = start, curr = 0, odd = 0; i < size(nums); ++i, odd ^= 1) {
14+
curr = !odd ? curr + nums[i] : max(curr - nums[i], 0L);
15+
result = max(result, curr);
16+
}
17+
return result;
18+
}
19+
};

0 commit comments

Comments
 (0)