1800: Maximum-Ascending-Subarray-Sum
Easy
table of contents
Just iterate through nums, keeping track of the
current sum using counter when
nums[i-1] < nums[i] and the maximum sum
using ans by making it equal to the largest value between
ans and counter everytime the current
subarray stops ascending.
code
class Solution {
public:
int longestMonotonicSubarray(vector<int>& nums) {
int ans = 1;
int counter = 1;
int direction = 0;
for (int i = 1; i < nums.size(); ++i) {
if (nums[i-1] != nums[i]) {
if (direction == ((nums[i-1] < nums[i]) ? 1 : -1)) {
++counter;
} else {
direction = (nums[i-1] < nums[i]) ? 1 : -1;
ans = max(ans, counter);
counter = 2;
}
} else {
direction = 0;
ans = max(ans, counter);
counter = 0;
}
}
ans = max(ans, counter);
return ans;
}
};