Maximum Ascending Subarray Sum

We’ll need to find the maximum possible sum of an ascending subarray in the given array nums.

Approach

  1. Initialize Variables: We’ll initialize two variables - current_sum and max_sum. The current_sum will be used to keep track of the sum of the current ascending subarray, and max_sum will store the maximum sum found so far.

  2. Iterate Through the Array: We’ll go through the array from the beginning to the end. For each number, we’ll check whether it is greater than the previous number.

  3. Update Current Sum: If the current number is greater than the previous one, we’ll add it to the current_sum. Otherwise, the ascending subarray has ended, and we’ll:

    • Compare the current_sum with max_sum, and update max_sum if current_sum is greater.
    • Reset current_sum to the current number, as we are starting a new subarray.
  4. Final Comparison: After the loop ends, we’ll do one final comparison between current_sum and max_sum to make sure we don’t miss the last ascending subarray.

  5. Return Result: We’ll return the value of max_sum, which is our answer.

Code Implementation

Here’s the code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
    def maxAscendingSum(self, nums: List[int]) -> int:
        max_sum = 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]

        max_sum = max(max_sum, current_sum)
        
        return max_sum

Key Takeaways

  • The code goes through the array once, making it an efficient solution.
  • By keeping track of the current ascending subarray sum and updating the maximum sum as needed, we find the required answer without needing to store all the subarrays.
  • This approach takes constant extra space, making it space-efficient.

This code will find and return the maximum sum of an ascending subarray from the given array of positive integers.