Maximum Ascending Subarray Sum - Leetcode 1800 - Python
Skills:
Systems Design Basics80%
Key Takeaways
The video solves LeetCode problem 1800, Maximum Ascending Subarray Sum, using a Brute Force solution and then optimizes it using a sliding window algorithm, ultimately achieving a linear time complexity and constant space complexity solution in Python.
Full Transcript
hey everyone welcome back and let's write some more neat code today so today let's solve the problem maximum ascending subay sum surprisingly an easy problem today but I'm recording this in advance so I don't know when this is actually going to be the daily problem but in this problem we are given an input array so let's consider the first example let's say this is the input array what we want to do is find the subarray which is basically just a contiguous part of the original array maybe the entire thing maybe just a single El element maybe this part and we want to identify the subarray such that we maximize the entire subarray sum so if you look at this subarray for example the entire sum is going to be 60 10 + 20 + 30 or maybe you could look at this subarray over here which is going to be 5 + 10 + 50 that's going to be 65 so this is bigger than this one and if you look at the output for this example 65 is the result that is actually the subarray that we want to identify and the reason for that is the reason we can't just take the entire subarray is because we want to ensure that for the subay that we choose in this case this one that the elements are in strictly increasing order they use the word ascending order so five is less than the next element which is 10 Which is less than the next element which is 50 if we try to add the 30 we see that that no longer holds we cannot include the 30 I mean I guess we could include the 30 if we wanted to but in that case we couldn't include the next element and if we can't include the next element then we kind of broke the contiguous part of this so even though like you could get rid of these two elements and say well 50 is bigger than 30 well now it's not contiguous anymore so you get rid of all of these and then you find okay well maybe the previous elements before 30 well yes 20 is less than 30 and then 10 is less than 20 so this is a valid subay but the sum is 60 it's not maximal we found the maximum subarray sum with the other subarray so how do you approach this problem well I think obviously there is a Brute Force solution and The Brute Force solution actually can lead you to the optimal solution The Brute Force would look something like this where we would have a couple nested for loops and the overall time complexity would end up being n squ it would look roughly like this where we start here we're at 10 so we could say this is our current subay sum and then we just want to expand as far right as we possibly can given this starting point so we see okay 10 that's bigger 30 that's bigger than the previous one five okay that's not quite bigger so we have to stop here this is the biggest one we could create starting from here now we could do something very very naive we could with the root Force solution say okay that's the best I could do starting from here but what's the best I could do starting from the second element and that would be 20 and 30 so I I want to show you the repeated work so this was the first iteration and then next I'm going to do this 20 and 30 and I can't go any further and then once again I'm going to try to find the biggest one starting from the third element and not to my surprise we still can't go any further this one was 30 okay now we do the same thing starting from the next element five and then 10 and then 50 and then we really can't go any further because there aren't any more elements we could do the same thing starting from this element 1050 and then finally we get uh the last element itself which is just 50 I think this picture is in some ways enough to identify the repeated work specifically it is this if I start at an element and I can find elements that are in increasing order well I'm going to do so I'm going to keep expanding as far as I can and then this is my stopping point I cannot go any further than that in addition we are guaranteed this is very important that every number in the input is going to be positive so it's not like this was a -10 if this was a -10 that would have actually been a problem because then yeah maybe this subarray over here could have actually been bigger than this one but given that all values are going to be positive that's not possible how could the next subet which is definitely going to end at the exact same position going to ever have a bigger sum than the the one we already calculated well it's not going to so what exactly is the solution in this well I wouldn't say it's precisely the sliding window uh algorithm but it does feel like a sliding window algorithm because what we're kind of doing is saying this is our starting point expand far to the right as you possibly can and then you found the stopping point okay can't go any further so next for the starting point we should shift it from here all the way to the next element because we can skip all of these subarrays we already know all of them are going to have a smaller sum than the one we just calculated we can skip those and so the way we're going to implement this is not by actually having two pointers that's why I'm saying it's not quite the sliding window algorithm what we're really going to do is this we're going to have a variable like the current sum which is going to tell us what the current sum is so first it'll be 10 then 10 + 20 then 10 + 20 + 30 so it'll be 60 and every step will also maintain what the result is which is going to be the maximum current sum that we've ever seen now this is what we're going to do once we get to the stopping point we're here we go to the next element we want to reset the current sum back down to zero and then add the next element so then set it to be five It's a Brand New Start it's a fresh start for us here and then we kind of do the same thing we just expand next element plus 10 next element is indeed bigger than this one so + 50 remember how did we identify this stopping point because the elements that are adjacent were not in increasing order 5 is not greater than 30 one tiny little Edge case that I think is probably worth mentioning is how we're going to go about implementing this because at every step we are going to look at two adjacent elements so if my pointer is over here my eye pointer then I want to look at the previous element and just make sure this value is greater than the previous one so the way I'm actually going to implement this algorithm is like this I'm going to have my current sum initially I'm actually going to set it to the first value which is going to be 10 and I'm also just going to set my result to that as well I don't really need to initialize it to zero I could that' probably be fine but setting it to the first value is also fine and then I'm actually not going to start my ey pointer at the first element I'm actually going to start it at the next element so now I can compare this with the previous one and it's greater so what I'm going to do is add a 20 to current so now it'll be 30 I'm going to update my result it's also 30 now I'm going to move my ey pointer here again compar with the previous it's bigger so I add 30 now my current is going to be 60 I can update the result as well next my ey pointer is going to be over here I look at the previous element it's not bigger so now is when I reset now I can reset my current value back down to this so it's going to be five now I could try to update my result but 60 is still the maximum that we've seen and next it's going to be a pretty quick so uh I'll get to 10 10 is bigger now my current will be 15 still we don't update the result once again my ey pointer is going to be shifted I'm at 50 now the value is bigger than the previous so we add 50 our current will be 65 and now we can update our result so this will be 65 and now we can't really go any further so this is what we would return so the nice thing about this solution is as you can see it just scans through the input once we uh reduce the time complexity from n^2 to linear and we don't need any extra data structures so the space complexity is constant now let's code it up so like I said I'm going to have two variables current is initially going to be the first element I think we're guaranteed that the array is going to be non-empty so we can actually get away with doing this and result is going to be the same I could just set it to Cur or the first element doesn't really matter that's what we're going to end up returning but not before we actually maximize it so we're going to go like this I in range length of nums but that's not our starting point we actually want to start at one and then go up until the end of the array so just like that the most important thing to do is the comparison we want to compare a nums of I with nums of I minus one we want to make sure that this is the case that the current element is bigger than the previous one so the way I could code this up is something like this I could say if else if it's true then we just add to current the element that we're looking at right now if it's not true then we could res Set current to the current element that we're looking at not including any of the previous values that we've seen and then after we've done that I think we could uh update our result like this try to maximize it and set it to the max of Cur and itself this will work let's give it a run you can see it's pretty efficient can't really do much better than this but if you prefer to write it without the if else it's actually possible you could do this you could change this to the not so kind of the ation I could have made this like greater than or equal as well but I'm just going to write it this way cuz I think this is also fine and so if that was not the case what we'd want to do is reset current just like we did in the else case but we could also actually be a little clever and set it to zero because if we do that then we can say we don't need an else statement and we could always take the current number and add it to Cur like this now this is really not an improvement over the previous solution in some ways I think this is less readable but I think it's worth showing you cuz usually in the medium and hard problems I always write code like this so I think it's kind of worth knowing some of these like little clever tricks so let me run this now and you can see here it also works if you found this helpful check out n code. thanks for watching and I'll see you soon
Original Description
🚀 https://neetcode.io/ - A better way to prepare for Coding Interviews
🧑💼 LinkedIn: https://www.linkedin.com/in/navdeep-singh-3aaa14161/
🐦 Twitter: https://twitter.com/neetcode1
⭐ BLIND-75 PLAYLIST: https://www.youtube.com/watch?v=KLlXCFG5TnA&list=PLot-Xpze53ldVwtstag2TL4HQhAnC8ATf
Problem Link: https://leetcode.com/problems/maximum-ascending-subarray-sum/
0:00 - Read the problem
0:30 - Drawing Explanation
8:05 - Coding Explanation
leetcode 1800
#neetcode #leetcode #python
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from NeetCodeIO · NeetCodeIO · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Leetcode 149 - Maximum Points on a Line - Python
NeetCodeIO
Design Linked List - Leetcode 707 - Python
NeetCodeIO
Minimum Time to Collect All Apples in a Tree - Leetcode 1443 - Python
NeetCodeIO
Design Browser History - Leetcode 1472 - Python
NeetCodeIO
Number of Good Paths - Leetcode 2421 - Python
NeetCodeIO
Flip String to Monotone Increasing - Leetcode 926 - Python
NeetCodeIO
Maximum Sum Circular Subarray - Leetcode 918 - Python
NeetCodeIO
Find Closest Node to Given Two Nodes - Leetcode 2359 - Python
NeetCodeIO
Concatenated Words - Leetcode 472 - Python
NeetCodeIO
Data Stream as Disjoint Intervals - Leetcode 352 - Python
NeetCodeIO
LFU Cache - Leetcode 460 - Python
NeetCodeIO
N-th Tribonacci Number - Leetcode 1137
NeetCodeIO
Best Team with no Conflicts - Leetcode 1626 - Python
NeetCodeIO
Greatest Common Divisor of Strings - Leetcode 1071 - Python
NeetCodeIO
Shortest Path in a Binary Matrix - Leetcode 1091 - Python
NeetCodeIO
Insert into a Binary Search Tree - Leetcode 701 - Python
NeetCodeIO
Delete Node in a BST - Leetcode 450 - Python
NeetCodeIO
Shuffle the Array (Constant Space) - Leetcode 1470 - Python
NeetCodeIO
Fruits into Basket - Leetcode 904 - Python
NeetCodeIO
Number of Subarrays of size K and Average Greater than or Equal to Threshold - Leetcode 1343 Python
NeetCodeIO
Naming a Company - Leetcode 2306 - Python
NeetCodeIO
As Far from Land as Possible - Leetcode 1162 - Python
NeetCodeIO
Shortest Path with Alternating Colors - Leetcode 1129 - Python
NeetCodeIO
Minimum Fuel Cost to Report to the Capital - Leetcode 2477 - Python
NeetCodeIO
Count Odd Numbers in an Interval Range - Leetcode 1523 - Python
NeetCodeIO
Contains Duplicate II - Leetcode 219 - Python
NeetCodeIO
Path with Maximum Probability - Leetcode 1514 - Python
NeetCodeIO
Add to Array-Form of Integer - Leetcode 989 - Python
NeetCodeIO
Unique Paths II - Leetcode 63 - Python
NeetCodeIO
Minimum Distance between BST Nodes - Leetcode 783 - Python
NeetCodeIO
Design Hashmap - Leetcode 706 - Python
NeetCodeIO
Range Sum Query Immutable - Leetcode 303 - Python
NeetCodeIO
Binary Tree Zigzag Level Order Traversal - Leetcode 103 - Python
NeetCodeIO
Middle of the Linked List - Leetcode 876 - Python
NeetCodeIO
Course Schedule IV - Leetcode 1462 - Python
NeetCodeIO
Single Element in a Sorted Array - Leetcode 540 - Python
NeetCodeIO
Capacity to Ship Packages - Leetcode 1011 - Python
NeetCodeIO
IPO - Leetcode 502 - Python
NeetCodeIO
Minimize Deviation in Array - Leetcode 1675 - Python
NeetCodeIO
Longest Turbulent Array - Leetcode 978 - Python
NeetCodeIO
Last Stone Weight II - Leetcode 1049 - Python
NeetCodeIO
Construct Quad Tree - Leetcode 427 - Python
NeetCodeIO
Find Duplicate Subtrees - Leetcode 652 - Python
NeetCodeIO
Sort an Array - Leetcode 912 - Python
NeetCodeIO
Ones and Zeroes - Leetcode 474 - Python
NeetCodeIO
Remove Duplicates from Sorted Array II - Leetcode 80 - Python
NeetCodeIO
Maximum Twin Sum of a Linked List - Leetcode 2130 - Python
NeetCodeIO
Concatenation of Array - Leetcode 1929 - Python
NeetCodeIO
Symmetric Tree - Leetcode 101 - Python
NeetCodeIO
Check Completeness of a Binary Tree - Leetcode 958 - Python
NeetCodeIO
Construct Binary Tree from Inorder and Postorder Traversal - Leetcode 106 - Python
NeetCodeIO
Find Peak Element - Leetcode 162 - Python
NeetCodeIO
Accounts Merge - Leetcode 721 - Python
NeetCodeIO
Binary Tree Preorder Traversal (Iterative) - Leetcode 144 - Python
NeetCodeIO
Binary Tree Postorder Traversal (Iterative) - Leetcode 145 - Python
NeetCodeIO
Number of Zero-Filled Subarrays - Leetcode 2348 - Python
NeetCodeIO
Minimum Score of a Path Between Two Cities - Leetcode 2492 - Python
NeetCodeIO
Sqrt(x) - Leetcode 69 - Python
NeetCodeIO
Successful Pairs of Spells and Potions - Leetcode 2300 - Python
NeetCodeIO
Optimal Partition of String - Leetcode 2405 - Python
NeetCodeIO
More on: Systems Design Basics
View skill →Related AI Lessons
⚡
⚡
⚡
⚡
Bloom Filters, Explained Properly
Dev.to · Daksh Gargas
Prefix Sums: The Preprocessing Trick That Makes Range Queries Instant
Medium · Programming
I Thought I Was Ready for the Interview — Then One Simple Math Question Destroyed Me
Medium · Programming
Week 2(Day 10): LeetCode Two Pointers(slow & fast): Remove Duplicates from Sorted Array (Brute…
Medium · Python
Chapters (3)
Read the problem
0:30
Drawing Explanation
8:05
Coding Explanation
🎓
Tutor Explanation
DeepCamp AI