Skip to content

1800. Maximum Ascending Subarray Sum 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  int maxAscendingSum(vector<int>& nums) {
    int ans = 0;
    int sum = nums[0];

    for (int i = 1; i < nums.size(); ++i)
      if (nums[i] > nums[i - 1]) {
        sum += nums[i];
      } else {
        ans = max(ans, sum);
        sum = nums[i];
      }

    return max(ans, sum);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public int maxAscendingSum(int[] nums) {
    int ans = 0;
    int sum = nums[0];

    for (int i = 1; i < nums.length; ++i)
      if (nums[i] > nums[i - 1]) {
        sum += nums[i];
      } else {
        ans = Math.max(ans, sum);
        sum = nums[i];
      }

    return Math.max(ans, sum);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def maxAscendingSum(self, nums: list[int]) -> int:
    ans = 0
    sum = nums[0]

    for i in range(1, len(nums)):
      if nums[i] > nums[i - 1]:
        sum += nums[i]
      else:
        ans = max(ans, sum)
        sum = nums[i]

    return max(ans, sum)