#1800
Maximum Ascending Subarray Sum
EasyArrayTwo PointersSliding WindowArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution uses a single pass through the array, maintaining a running sum of the current ascending subarray and updating the maximum sum as needed. This is efficient and avoids unnecessary calculations.
⚙️
Algorithm
5 steps- 1Step 1: Initialize variables for the maximum sum and the current sum.
- 2Step 2: Iterate through the array starting from the second element.
- 3Step 3: If the current element is greater than the previous one, add it to the current sum.
- 4Step 4: If not, reset the current sum to the current element.
- 5Step 5: Update the maximum sum if the current sum exceeds it.
solution.py9 lines
1def maxAscendingSum(nums):
2 max_sum = current_sum = nums[0]
3 for i in range(1, len(nums)):
4 if nums[i] > nums[i - 1]:
5 current_sum += nums[i]
6 else:
7 current_sum = nums[i]
8 max_sum = max(max_sum, current_sum)
9 return max_sumℹ
Complexity note: The time complexity is O(n) because we only traverse the array once. The space complexity is O(1) since we only use a few variables for tracking sums.
- 1The end of an ascending subarray marks the start of a new potential subarray.
- 2Tracking the current sum allows for efficient updates without re-evaluating previous elements.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.