Maximum Ascending Subarray Sum - Problem

Imagine you're analyzing stock prices throughout a day, looking for the longest streak of consecutive price increases that gives you the maximum profit potential. This is exactly what we're solving here!

Given an array of positive integers nums, your task is to find the maximum possible sum of a strictly ascending (increasing) subarray.

Key Points:

  • A subarray is a contiguous sequence of elements
  • Strictly ascending means each element must be larger than the previous one
  • We want the sum of such a subarray that gives us the maximum value

Example: In [10,20,30,5,10,50], the ascending subarrays are [10,20,30] (sum=60), [5,10,50] (sum=65), and single elements. The answer is 65.

Input & Output

example_1.py โ€” Basic Ascending Sequence
$ Input: [10,20,30,5,10,50]
โ€บ Output: 65
๐Ÿ’ก Note: We have two ascending subsequences: [10,20,30] with sum 60, and [5,10,50] with sum 65. The maximum is 65.
example_2.py โ€” Multiple Single Elements
$ Input: [10,20,30,40,50]
โ€บ Output: 150
๐Ÿ’ก Note: The entire array is strictly ascending, so we sum all elements: 10+20+30+40+50 = 150.
example_3.py โ€” Decreasing Array
$ Input: [12,17,15,13,10,11,12]
โ€บ Output: 33
๐Ÿ’ก Note: The longest ascending subsequence is [10,11,12] at the end with sum 33. Other sequences like [12,17] have smaller sums.

Visualization

Tap to expand
๐Ÿ“ˆ Stock Rally Analysis VisualizationStock Prices: $10 โ†’ $20 โ†’ $30 โ†’ $5 โ†’ $10 โ†’ $50$0$25$50Day 1Day 2Day 3Day 4Day 5Day 6Rally 1: $10+$20+$30 = $60Rally 2: $5+$10+$50 = $65๐ŸŽฏ Key Insight: One-Pass Rally DetectionJust like tracking stock rallies, we scan prices once from left to right.When prices drop, we know the rally ended, so we start tracking a new one.We always remember the most profitable rally we've seen so far!
Understanding the Visualization
1
Track Current Rally
Keep running total of current consecutive price increases
2
Detect Rally End
When price drops or stays same, current rally ends
3
Start New Rally
Begin tracking new rally from current price point
4
Remember Best Rally
Always keep track of the most profitable rally seen so far
Key Takeaway
๐ŸŽฏ Key Insight: Like finding the best stock rally, we only need one pass through the data. When the trend breaks, we immediately start fresh while remembering our best performance so far.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass through the array, each element processed once

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only using two variables to track current and maximum sums

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 100
  • 1 โ‰ค nums[i] โ‰ค 100
  • All integers are positive
Asked in
Amazon 15 Google 12 Microsoft 8 Meta 5
31.2K Views
Medium Frequency
~15 min Avg. Time
1.3K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen