My approach started with two variables: max_sum
to store the highest sum found and current_sum
to keep track of the running sum of the current ascending subarray. Starting with the first element, I iterated through the array. If the current number is greater than the previous one, I will add it to current_sum
. Otherwise, I will update max_sum
if current_sum
is larger, then reset current_sum
to the current number.
At the end of the loop, I will return the maximum of max_sum
and current_sum
to account for the last subarray.
class Solution:
def maxAscendingSum(self, nums: List[int]) -> int:
max_sum = 0
current_sum = nums[0]
for i in range(1, len(nums)):
if nums[i] > nums[i - 1]:
current_sum += nums[i]
else:
max_sum = max(max_sum, current_sum)
current_sum = nums[i]
return max(max_sum, current_sum)
- Time: O(n)
- Space: O(1)
