1800. Maximum Ascending Subarray Sum
UnknownView on LeetCode
Time: O(n)
Space: O(1)
Advertisement
Intuition
Find the subarray of 1s with maximum length (since max sum of consecutive ascending array starting from 1 = 1+2+...+L = L*(L+1)/2 but actually just sum consecutive increasing prefix).
Algorithm
- 1Sliding window: longest consecutive subarray where each element = previous + 1.
- 2Max sum = max(sum of such a window).
Common Pitfalls
- •The maximum ascending subarray sum (each element strictly greater than previous).
1800.cs
C#
// Approach: Linear scan maintaining running sum of current ascending subarray; reset on non-increase.
// Time: O(n) Space: O(1)
public class Solution
{
public int MaxAscendingSum(int[] nums)
{
int maxSum = 0;
int sum = nums[0];
for (int i = 1; i < nums.Length; i++)
{
if (nums[i] > nums[i - 1])
sum += nums[i];
else
{
maxSum = Math.Max(maxSum, sum);
sum = nums[i];
}
}
return Math.Max(maxSum, sum);
}
}Advertisement
Was this solution helpful?