You are given an array of positive integers nums, return the maximum possible sum of an strictly increasing subarray in nums.
A subarray is defined as a contiguous sequence of numbers in an array.
Note: An array is said to be strictly increasing if each element is strictly greater than its previous one (if exists).
Example 1:
Input: nums = [10,20,30,5,10,50]
Output: 65Explanation: [5,10,50] is the ascending subarray with the maximum sum of 65.
Example 2:
Input: nums = [10,20,30,40,50]
Output: 150Explanation: [10,20,30,40,50] is the ascending subarray with the maximum sum of 150.
Example 3:
Input: nums = [12,17,15,13,10,11,12]
Output: 33Explanation: [10,11,12] is the ascending subarray with the maximum sum of 33.
Constraints:
1 <= nums.length <= 1001 <= nums[i] <= 100Before attempting this problem, you should be comfortable with:
An ascending subarray is a contiguous sequence where each element is strictly greater than the previous. We want the maximum sum among all such subarrays.
The brute force approach considers every possible starting position. From each start, we extend the subarray as long as elements keep increasing, accumulating the sum. We track the maximum sum seen across all starting positions.
res = 0 to store the maximum sum found.i:curSum = nums[i].j = i + 1 while nums[j] > nums[j-1]:nums[j] to curSum.res = max(res, curSum).res.We can solve this in a single pass. As we scan through the array, we maintain a running sum of the current ascending subarray. Whenever we encounter an element that does not continue the ascending pattern, we reset the running sum and start a new subarray from that element.
This works because ascending subarrays are naturally separated by positions where the ascending condition breaks.
res = nums[0] and curSum = nums[0].i from 1 to n-1:nums[i] <= nums[i-1], reset curSum = 0.nums[i] to curSum.res = max(res, curSum).res.The problem requires strictly ascending elements, meaning each element must be greater than the previous one. Using >= instead of > when checking the ascending condition will incorrectly include equal consecutive elements in your subarray, leading to wrong answers.
A single element by itself forms a valid ascending subarray. If you forget to consider this case or initialize your result incorrectly, you might miss the maximum when the answer is a single large element surrounded by non-ascending neighbors.