You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardexpand all lines: solution/2000-2099/2036.Maximum Alternating Subarray Sum/README_EN.md
+45-28
Original file line number
Diff line number
Diff line change
@@ -53,18 +53,25 @@ The alternating subarray sum is 1.
53
53
54
54
## Solutions
55
55
56
+
**Solution 1: Dynamic Programming**
57
+
58
+
We define $f$ as the maximum alternating subarray sum ending with $nums[i]$, and $g$ as the maximum alternating subarray sum ending with $-nums[i]$. Initially, $f$ and $g$ are both $-\infty$.
59
+
60
+
Next, we traverse the array $nums$. For each position $i$, we need to maintain the values of $f$ and $g$, which are $f = \max(g, 0) + nums[i]$ and $g = f - nums[i]$, respectively. The answer is the maximum value among all $f$ and $g$.
61
+
62
+
The time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$.
0 commit comments