Skip to content

Commit c7b6ac7

Browse files
committed
Sync LeetCode submission Runtime - 0 ms (100.00%), Memory - 17.8 MB (28.05%)
1 parent e7607e1 commit c7b6ac7

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
<p>Given an array of positive integers <code>nums</code>, return the <em>maximum possible sum of an <strong>ascending</strong> subarray in </em><code>nums</code>.</p>
2+
3+
<p>A subarray is defined as a contiguous sequence of numbers in an array.</p>
4+
5+
<p>A subarray <code>[nums<sub>l</sub>, nums<sub>l+1</sub>, ..., nums<sub>r-1</sub>, nums<sub>r</sub>]</code> is <strong>ascending</strong> if for all <code>i</code> where <code>l &lt;= i &lt; r</code>, <code>nums<sub>i </sub> &lt; nums<sub>i+1</sub></code>. Note that a subarray of size <code>1</code> is <strong>ascending</strong>.</p>
6+
7+
<p>&nbsp;</p>
8+
<p><strong class="example">Example 1:</strong></p>
9+
10+
<pre>
11+
<strong>Input:</strong> nums = [10,20,30,5,10,50]
12+
<strong>Output:</strong> 65
13+
<strong>Explanation: </strong>[5,10,50] is the ascending subarray with the maximum sum of 65.
14+
</pre>
15+
16+
<p><strong class="example">Example 2:</strong></p>
17+
18+
<pre>
19+
<strong>Input:</strong> nums = [10,20,30,40,50]
20+
<strong>Output:</strong> 150
21+
<strong>Explanation: </strong>[10,20,30,40,50] is the ascending subarray with the maximum sum of 150.
22+
</pre>
23+
24+
<p><strong class="example">Example 3:</strong></p>
25+
26+
<pre>
27+
<strong>Input:</strong> nums = [12,17,15,13,10,11,12]
28+
<strong>Output:</strong> 33
29+
<strong>Explanation: </strong>[10,11,12] is the ascending subarray with the maximum sum of 33.
30+
</pre>
31+
32+
<p>&nbsp;</p>
33+
<p><strong>Constraints:</strong></p>
34+
35+
<ul>
36+
<li><code>1 &lt;= nums.length &lt;= 100</code></li>
37+
<li><code>1 &lt;= nums[i] &lt;= 100</code></li>
38+
</ul>
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# Approach 2: Linear Scan
2+
3+
# Time: O(n)
4+
# Space: O(1)
5+
6+
class Solution:
7+
def maxAscendingSum(self, nums: List[int]) -> int:
8+
max_sum = 0
9+
curr_subarray_sum = nums[0]
10+
11+
for curr_idx in range(1, len(nums)):
12+
if nums[curr_idx] <= nums[curr_idx - 1]:
13+
# If the current element is not greater than the previous one, update maxSum
14+
max_sum = max(max_sum, curr_subarray_sum)
15+
curr_subarray_sum = 0
16+
curr_subarray_sum += nums[curr_idx]
17+
18+
# Final check after the loop ends to account for the last ascending subarray
19+
return max(max_sum, curr_subarray_sum)
20+

0 commit comments

Comments
 (0)