You are given an integer array nums
. A subarray of nums
is called an ascending subarray if it is a contiguous non-empty sequence of elements such that for all i
, nums[i] < nums[i + 1]
. The sum of an ascending subarray is the sum of its elements.
Return the maximum sum of any ascending subarray.
Example:
Input: nums = [10, 20, 30, 5, 10, 50]
Output: 65
Explanation: [10, 20, 30] and [5, 10, 50] are the two ascending subarrays with the maximum sum of 60 and 65 respectively. Thus, we return 65.
nums
contain negative numbers?
nums
is empty?
nums
is empty, the function should return 0.To solve this problem, we will use the following approach:
max_sum
to store the maximum sum found so far, initialized to 0 (or to the first element if nums
is not empty).current_sum
to store the sum of the current ascending subarray, initialized to 0.current_sum
.current_sum
with max_sum
to keep track of the maximum sum found so far, then reset current_sum
to the current element.After finishing the loop, there might still be an unsaved current_sum
since the last subarray might be the maximum ascending one. Compare and save it if necessary.
max_sum
.Here is the Python code implementing the above strategy:
def maxAscendingSum(nums):
if not nums:
return 0
max_sum = 0
current_sum = nums[0]
for i in range(1, nums.length):
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
# Example usage
nums = [10, 20, 30, 5, 10, 50]
print(maxAscendingSum(nums)) # Output: 65
The time complexity of this solution is (O(n)), where (n) is the length of the input array nums
. This is because we iterate through the array exactly once. The space complexity is (O(1)) because we use a constant amount of extra space regardless of the input size.
Feel free to ask any more questions or provide input for additional modifications.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?