6 Stock Span Problem

Поделиться
HTML-код
  • Опубликовано: 10 фев 2025
  • The stock span problem is a financial problem where we have a series of n daily price quotes for a stock and we need to calculate span of stock’s price for all n days.
    The span Si of the stock’s price on a given day i is defined as the maximum number of consecutive days just before the given day, for which the price of the stock on the current day is less than or equal to its price on the given day.
    For example, if an array of 7 days prices is given as {100, 80, 60, 70, 60, 75, 85}, then the span values for corresponding 7 days are {1, 1, 1, 2, 1, 4, 6}
    Refer: www.geeksforge... .
    ------------------------------------------------------------------------------------------
    Here are some of the gears that I use almost everyday:
    🖊️ : My Pen (Used in videos too): amzn.to/38fKSM1
    👨🏻‍💻 : My Apple Macbook pro: amzn.to/3w8iZh6
    💻 : My gaming laptop: amzn.to/3yjcn23
    📱 : My Ipad: amzn.to/39yEMGS
    ✏️ : My Apple Pencil: amzn.to/3kMnKYf
    🎧 : My Headphones: amzn.to/3kMOzM7
    💺 : My Chair: amzn.to/385weqR
    🛋 : My Table: amzn.to/3kMohtd
    ⏰ : My Clock: amzn.to/3slFUV3
    🙋🏻‍♀️ : My girlfriend: amzn.to/3M6zLDK ¯\_(ツ)_/¯
    PS: While having good gears help you perform efficiently, don’t get under the impression that they will make you successful without any hard work.

Комментарии • 555

  • @jagrit07
    @jagrit07 4 года назад +463

    Thanks, man. @Aditya Verma
    Anyone who just watched the video for 5 minutes and they got the solution on their own should still like the video because He did hard work explaining it. And because of his previous videos, we were able to solve it.

    • @TheAdityaVerma
      @TheAdityaVerma  4 года назад +96

      Thanks brother, Do subscribe and share, that keeps me motivated to do more !!

    • @KeshavSingh-si4vm
      @KeshavSingh-si4vm 4 года назад +10

      @@TheAdityaVerma I am at NIT Surathkal and currently preparing for internship interviews . You DP videos are helping me a lot .

    • @mohsinabbassayyed9610
      @mohsinabbassayyed9610 4 года назад +1

      @@TheAdityaVerma what if the given array is [100 86 78 89 1000]

    • @chillguyy.99
      @chillguyy.99 3 года назад

      true

    • @mayankverma8989
      @mayankverma8989 3 года назад +2

      @@mohsinabbassayyed9610 ngl of 1000 will be -1 and index of 1000 is 4 so if u do ngl index-i that is 4-(-1)=5 will be the answer

  • @AP-bk8vq
    @AP-bk8vq 4 года назад +290

    Amazing work.. even paid courses don't have explanations anywhere near this level..Please make videos on Graph too!

  • @Kirti-bi2yj
    @Kirti-bi2yj 9 месяцев назад +16

    A more optimized solution, rather than storing pair in the stack, we can just solely store the NGL index itself, that will also work :
    vector calculateSpan(int price[], int n)
    {
    vector ans;
    stack s;
    for(int i=0; i

    • @aub1729
      @aub1729 5 месяцев назад +1

      dangg that's good!

    • @tarandeepsingh4291
      @tarandeepsingh4291 Месяц назад

      you don't need that separate loop for populating ans vector, you can do it on the go:
      vector calculateSpan(vector& v) {
      // write code here
      int n = v.size();
      stack st;
      vector ans(n,-1);
      for(int i = 0;i

  • @shivangirastogi1539
    @shivangirastogi1539 4 года назад +83

    This is my first ever comment on you tube and without a single doubt your teaching skills make me do that. Great Work Man ☺️
    Eagerly waiting for new playlists..

  • @suyashdubey520
    @suyashdubey520 4 года назад +69

    Watching this again for nostalgia's sake.

  • @nikhil6842
    @nikhil6842 3 года назад +12

    I saw the explanation of this question in a very famous paid course. However they still failed to mention the intuition of arriving at this solution using stack, loved how you broke it into the NGL problem and the overall intuition behind it

  • @divyanshusaxena148
    @divyanshusaxena148 4 года назад +162

    i bet IITians are watching videos of this NIT guy. Good going man.

  • @dashrathsinghkaviya
    @dashrathsinghkaviya 3 года назад +4

    Bhaiya aap na main last year main hu tier 3 clg mein and maine dsa start kr rkhi h to stacks search kia to aapki videos mili...and aap manoge nhi mera concept itna awsm bn rha h na stacks mein ki kya hi btau...schi mein kafi shi pdhate ho aap... great job...keep it up... I've subscribed too... Thanks for making my concepts clear... FROM JAIPUR

  • @tarangranpara5913
    @tarangranpara5913 4 года назад +5

    the way you connected with NGL problem, hats off brother. you're an inspiration.

  • @ahishnar1568
    @ahishnar1568 3 года назад +3

    Got the solution at 2:59 only, that how we can solve this.
    Great great great great great coding, programming, problem solving master.
    The only person who made not only dp but entire programming and problem solving easy.
    The guy who made entire programming and problem solving easy.
    Hats off to you bro. 🤘🤘🤘😀☺️🎉🎉🎉🙏🙏🙏🙏🙏🙏

  • @mvabhinav1998
    @mvabhinav1998 3 года назад +20

    Awesome series. I was able to it myself 😃
    I wish he made videos for rest of the topics as well. He is an amazing teacher !!
    Thankyou aditya

  • @coding_bro4158
    @coding_bro4158 Год назад +5

    i have not seen any playlist of this channel other than this stack playlist......but i must say, its killing it. My stack understanding and problem solving has improved a lot , every other channel like anuj bhaiya , love baber , khuswaha has not explained as clear as him. Thank u @Aditya Verma Bhaiya😇

  • @rishabhgupta734
    @rishabhgupta734 3 года назад +1

    just commenting to remind you that even after 1 year this video is helping many people like me. KUDOS to you.

  • @Ayush-bk3rv
    @Ayush-bk3rv 2 года назад +1

    The first Four Foundation problem was a neat trick before getting to this problem, you made the viewer use his intuition to get to the solution.

  • @coldfinger3472
    @coldfinger3472 3 года назад +1

    There may be many better programmer than you, but I have not seen better teacher than you for sure. The way you teach in flow is soo dope. thank you so much.

  • @dochimekashiariri7610
    @dochimekashiariri7610 3 года назад +7

    I found one more thing in my life to be thankful for 🥺.

  • @vineetswami376
    @vineetswami376 2 года назад +3

    Almost three year passes, but no one can make better content then you, you are such a genious.

  • @priyanshigupta1359
    @priyanshigupta1359 3 года назад +1

    apko kaise thanks bolo bhaiya ...aap itna acha padhate ho mujhse stack ke ques solve hone lge...thanks bhaiya

  • @criminalcoder6307
    @criminalcoder6307 4 года назад +2

    I'm a fresher and I completed all the data structures playlist .
    Thanks

  • @milimishra6447
    @milimishra6447 4 года назад +2

    first time someone explained like this............great content..thanksssssssssssssss alot..u r amazingggggggggggggggggggggggggggggggg..

  • @neerajmahapatra5239
    @neerajmahapatra5239 3 года назад +1

    I just imagined the explanation just by hearing the problem statement hats off to you
    ..

  • @YashHalgaonkar
    @YashHalgaonkar 3 года назад +2

    Just watched the explanation of the question. Got the intuition and solved it on my own in less than 5 min. Amazing work @AdityaVerma!!

  • @bhavyamalviya8364
    @bhavyamalviya8364 3 года назад +3

    Thanks for taking time out from your schedule and sharing the knowledge with all of us

  • @Gauravkumar-kc6xh
    @Gauravkumar-kc6xh 3 года назад +2

    Wanted all dsa by you bro. You just rock the dsa.

  • @ankursharma6084
    @ankursharma6084 4 года назад +2

    Sucha a unique and beautiful way of teaching. You are really an awesome tutor. Yesterday i watched Coding Blocks video and today after watching your video i know that you are in a complete different level. And that also we get your outstanding content and experience for free. This is so thankful of you.

    • @b82tushar22
      @b82tushar22 4 года назад +1

      Kya beta, mjaa aa rha hai na!

  • @anshumansharma4580
    @anshumansharma4580 3 года назад +5

    I was able to do the answer myself after watching the problem statement part. Really these lectures are terrific.
    Instead of making an index vector, I simply made a pair with the answer that we have to return.
    So instead of traversing loop 2 times, we can do it in one traversal only.
    vector calculateSpan(int price[], int n)
    {
    // Your code here
    vector ans;
    stack S;
    for(int i=0;i

    • @anshulpandey6576
      @anshulpandey6576 2 года назад

      Same here bro . I too solved using same approach

  • @ASHISHSINGH-gs3yt
    @ASHISHSINGH-gs3yt Год назад

    Slight optimisation for time complexity
    Just store the index of the elements in the array and code as following :
    stack s;
    for(int i=0; i

  • @ay-tw4om
    @ay-tw4om Год назад

    there is a leetcode editorial for this question which has O(1) amortized time complexity. Running a for loop for each call to next() is not needed. The key idea behind this approach is that the "answer" for a previous "price" can be directly added to the current answer, if current price is greater.

  • @parvahuja7618
    @parvahuja7618 Год назад

    sir you are really the best teacher out there

  • @danishakhtar2683
    @danishakhtar2683 3 года назад +1

    Man you are good the way teach you is just incredible,subscribed and share done . I already recommended your DP playlist to my juniors !! LOVE FROM NITW!!

  • @PritamKumar-mr5dv
    @PritamKumar-mr5dv 4 года назад +1

    yes bhaiya zindagi me kohi batayga must phadtey ho app....huge support bhaiya.....

  • @suvam2perfect
    @suvam2perfect 4 года назад +51

    If I got your series 3 years back perhaps I might not waste my b.tech years 🙌

  • @abhishek2116
    @abhishek2116 2 года назад

    explain in very simple manner , thanks sir, now i am able to move standard/tough or tricky method

  • @Reels-fact-7
    @Reels-fact-7 11 месяцев назад +1

    thank you so much for easy explanation

  • @abhishekrattu
    @abhishekrattu 3 года назад

    The best person who is teaching in the BEST way! Very Very Helpful content :)

  • @divya5808
    @divya5808 4 года назад +2

    Hattsss off to you sir!! You are just remarkable and phenomenon!! Please do post more videos like this,so that we can learn more from you!Thanks alot!

  • @GauravKumar-dw2ml
    @GauravKumar-dw2ml 3 года назад

    I solved this question without using pair. As we can do price[s.top()] .Thanks @Aditya for such a strong foundation.

  • @bhargavi3681
    @bhargavi3681 Год назад

    Thank you so much for creating this videos. I have written the whole code by understanding the theory and with the help of previous videos. Great work sir. Thank you.🙏

  • @tusharjangid2492
    @tusharjangid2492 3 года назад +2

    Great work man, was really helpful.
    One can see depth of your grasp on what you teach.

  • @jayachandra677
    @jayachandra677 3 года назад

    ese problems mere dimag ke upar se jata hai aur yeh tutorial tho aag laga di. thanks bhaiya :)

  • @PabitraPadhy
    @PabitraPadhy 3 года назад +1

    I implemented this using a double stack method, but yours is cleaner.
    more importantly, it follows the same pattern as you said, so it's easier.

  • @vikaskumarnitrr
    @vikaskumarnitrr 2 года назад

    i have been watching your videos for quite sometime now,and i am able to solve/code just by watching your explanation thanks bhaiya and your identification techniques is just mind blowing

  • @nadeem2944
    @nadeem2944 2 года назад +1

    without using a pair in stack :
    #include
    vector findSpans(vector &price) {
    stack s ;
    int n = price.size() ;
    vector ans(n) ;
    for(int i = 0 ; i < n ; i++ ) {
    int curr = price[i] ;
    while( !s.empty() && price[s.top()]

  • @bismeetsingh352
    @bismeetsingh352 4 года назад +1

    Python Code:
    i=0
    while i0 and stack[-1][1]0:
    difference=i-stack[-1][0]
    ans.append(difference)
    else:
    ans.append(i+1)
    stack.append((i,arr[i]))
    i+=1
    print(ans)

  • @shrutijain2426
    @shrutijain2426 2 года назад

    Thanks @Aditya Verma. Your way of teaching is hands down the best. Even professors cannot teach in this way. Please make some videos on Queues and Linked Lists as well.

  • @priyasahu1439
    @priyasahu1439 4 года назад

    I am really fan of your way of teaching and explaining each and every concept

  • @LokeshSharmaCP
    @LokeshSharmaCP Год назад +1

    great bhai sach me zabardast...
    the flow.....😎

  • @AshishPal-ki8tr
    @AshishPal-ki8tr 3 года назад

    maine khud se kar liyaa ye question ,What a feeling!! thanks @Aditya Verma

  • @skritichauhan
    @skritichauhan 4 года назад +2

    your explainations are really amazing. Please make videos on bit manipulation questions too. With your explanations, students can easily master this topic as well

  • @utsavseth6573
    @utsavseth6573 Год назад

    Please please please Aditya bhai, Keep uploading videos. Your are one person who does not do any stupid things in video, explain properly, and it's all because of you that I am able to grasp the intuition, logic and flow correctly. Please dont stop making videos. Please make videos on graphs, trees, strings topics.

  • @varungupta5021
    @varungupta5021 4 года назад

    Bhaiya agar aapke jaisa professor college mai ho to sabka placement top product based company mai to hona hi hai. Appne question hi nai pura concept build kar diya Thanks for that!

  • @aisharawat9102
    @aisharawat9102 4 года назад

    Bhaiya keep adding more videos ...I don't have words to explain how helpful your videos are..

  • @sumitsaurabh8943
    @sumitsaurabh8943 3 года назад

    Heartly, First time I subscribed and liked any playlist on youtuve . Really your explanation is intresting .thanks

  • @Aadyagupta5679
    @Aadyagupta5679 3 года назад

    bhaiya i never think that, this question is total connect with NGL problem, the way you connect the problem is lit️. thank for providing such a great content!!

  • @LuciferScripts
    @LuciferScripts 2 года назад

    Great work. I saw two solution before this vdeo but no one explain as better as you. Thank You fron Pune Institute of Technology Pune, Maharashatra

  • @svworld01
    @svworld01 3 года назад

    Simplified Code in Java: github.com/svworld01/100DayOfCodingChallenge/blob/main/day2/StockSpanProblem.java

  • @tanyacharanpahadi158
    @tanyacharanpahadi158 4 года назад

    Brooo you are so awesome. All the people watching this video you are really lucky to have your placements after jan 2020.

  • @paritoshdadhich2954
    @paritoshdadhich2954 3 года назад +1

    Thank you for such a great explanation. You are a gem. I tried to solve this question, tbh I mug up the solution but today I can code it with and can teach it to anyone.
    Thanks a ton bhaiya

    • @ayushthakur2896
      @ayushthakur2896 3 года назад

      Mugging up soln is also a way specially in backtracking problems .... what do u think

    • @pratikgoswami2569
      @pratikgoswami2569 3 года назад

      waah bete moj kardi...tum toh bade heavy driver hoon

  • @avinashkumarrao9728
    @avinashkumarrao9728 2 года назад

    thanks bhaiya you are awesome the way you teach is very unique

  • @Aditya_6996
    @Aditya_6996 7 месяцев назад

    thanks bhaiya , amazing teaching skills !

  • @deepakjnvx
    @deepakjnvx Год назад

    I dont think that there is any need of stack of pair, we can solve the question by just using stack of int as following....
    vector calculateSpan(int price[], int n){
    vector ans;
    stack st;
    for(int i=0;i

  • @techlover714
    @techlover714 4 года назад +2

    Border problems aside. But you Indians are exceptional programmers.
    Love Aditya Verma from Pakistan.

    • @RathourShubham
      @RathourShubham 4 года назад

      No offence, but I have some questions. Why are you here? Do you even have codings there?

    • @techlover714
      @techlover714 4 года назад

      @@RathourShubhamunlike India, only rapes are not present in Pakistan. But otherwise we have many things in common.

  • @dhruvarora273
    @dhruvarora273 3 года назад +1

    Sir , thanks for providing these all important questions at one place.
    Sir, please upload the queue and linked list questions also .

  • @AyushGupta-ux4gq
    @AyushGupta-ux4gq Год назад +1

    class Solution
    {
    public:
    //Function to calculate the span of stock’s price for all n days.
    vector calculateSpan(int arr[], int n)
    {
    // Your code here
    stack st;
    int count=1;
    vector ans;
    for(int i=0;i

  • @jishulayek8252
    @jishulayek8252 4 года назад

    U are an amazing teacher. Always like how to build the intuition part. Keep the good work going.

  • @KCODivyanshuKatyan
    @KCODivyanshuKatyan 3 года назад

    never seen an explaination which is this good
    dammn awesome man hats off.....

  • @Chiragpanchal000
    @Chiragpanchal000 2 месяца назад

    Thanks a lot for this series Aditya. Just trying to optimize this further, we can also do this without 2nd for loop .
    const stockSpan = (arr: number[]): number[] => {
    const result: number[] = [];
    const stack = [];
    for (let i = 0; i < arr.length; i++) {
    if (stack.length > 0 && stack[stack.length - 1]?.value

  • @ashvinimeshram5242
    @ashvinimeshram5242 3 года назад

    Your teaching style us just amazing

  • @deveshsingh7257
    @deveshsingh7257 3 года назад +2

    rather than storing values in stack we can store index ,therefore ,we don't need pair

  • @rncsMahimaMahendru
    @rncsMahimaMahendru 4 года назад +1

    All your videos are amazing and super understandable please upload more soon!!

  • @sulekhakumari-hs4gy
    @sulekhakumari-hs4gy 4 года назад

    Thanks bro. Effectivelity utilizing my corona time watching your videos.

  • @theunusual4566
    @theunusual4566 4 месяца назад

    Thanks for explaining so wonderfully.
    The same code approach with slight modification :
    public static int[] calculateSpan(int price[], int n)
    {
    int[] result = new int[n];
    Stack stack= new Stack();
    for(int i=0; i

  • @unknownhacker8152
    @unknownhacker8152 Год назад

    Only index, we can put and while comparison we'll take array value at that index for java, bcoz there was no concept for pair, btw, thank you so much for great videos, i love it...

  • @sauravkumarlal896
    @sauravkumarlal896 4 года назад +4

    Thank you for the great content bhaiya, waiting for more videos...😍😍

  • @disharastogi5609
    @disharastogi5609 3 года назад

    amazing amazing explanation. You teach so well. Thanks a lot

  • @abhishekbabbar9234
    @abhishekbabbar9234 4 года назад +7

    best explanation i've ever seen for this problem... hats off brother...
    logic can be simplified to this also....-
    // java
    //pair is my class having 'val' ans 'ind' as two integer variables
    Stack st=new Stack();
    int ans[]=new int[n];
    for(int i=0;i

  • @raisanjeeb42
    @raisanjeeb42 2 года назад

    Solved without looking at the explanation.
    The concept explained in 1st question is enough to tackle these question. Thank You for ur teaching🙌🙌❤

  • @DeepakThakur-gn7yl
    @DeepakThakur-gn7yl 7 месяцев назад

    Mind blowing explanation bahiyan❤

  • @mohitmehta4143
    @mohitmehta4143 4 года назад +2

    Amazing explanations brother! Please make videos on the graph as well.

  • @devanshsrivastava3185
    @devanshsrivastava3185 3 года назад +1

    bhaiya please make more videos like this for different topics of data structures like trees, graphs etc. . LOve the way you teach thanks .

  • @adityaagarwal637
    @adityaagarwal637 4 года назад +6

    bhaiya ne bilkul jee wale tareke se pdaya hai , # mza aa gya :):):)

  • @amanmaurya7646
    @amanmaurya7646 8 месяцев назад

    without making stack of pair of index and value we can make a simple stack storing only indices..
    But it could be a bit confusing so you should use pair of stack only.

  • @shivamkasat6334
    @shivamkasat6334 4 года назад +41

    once I asked in my class group! how were you guys able to figure it out that this will be solved using stack ?
    And not a single person was able to answer it.
    but I know the answer now! Thanks!

  • @himanshugupta2407
    @himanshugupta2407 2 года назад

    og explaination big brother 🤩,looking forward to some amazing content from your side in future ,and the trick that u did with ur pen looks cool.

  • @harshita6683
    @harshita6683 Год назад

    Thankyou i was able to solve such questions finally!

  • @DroidHolicOfficial
    @DroidHolicOfficial 2 года назад +1

    Since we are dealing with indexes here. WE can just put indexes in the stack instead of the pair.
    calculateSpan(price, n)
    {
    let stack = [0];
    let output = new Array(n);
    output[0] = 1;
    for(let i = 1; i < n; i++){
    while(stack.length > 0){
    let topIndex = stack[stack.length - 1];
    let top = price[topIndex];
    if(top > price[i]){
    stack.push(i);
    output[i] = i - topIndex;
    break;
    } else{
    stack.pop();
    }
    }
    if(stack.length === 0){
    output[i] = i + 1;
    stack.push(i)
    }
    }
    return output;
    }

  • @prakharagarwal4933
    @prakharagarwal4933 4 года назад

    thank bhaiya... your videos are very well serving it purpose

  • @shreya-rs1fr
    @shreya-rs1fr 4 года назад

    we can make a single vector or array and directly push index of st.top() - I(index of element) instead of making two arrays and substracting them .

  • @SahilSharma-vl9rk
    @SahilSharma-vl9rk 4 года назад

    1 video dekhi bass nearest greater to right aage ke foundation waale khud se ban gye + stock span problem bhi khud se ban gaya
    what a great content

  • @minkiaggarwall5529
    @minkiaggarwall5529 4 года назад

    bhai tumne ds padi kese thoda share kardo bohat achai knowlrdge hai.
    sources and how to study..........best video ever seen

  • @sankalpverma5244
    @sankalpverma5244 3 года назад +3

    Sir, in Java there is no option for storing array element and its index together in stack, Kindly suggest any idea...

    • @kirtikhohal3313
      @kirtikhohal3313 2 года назад +1

      Just store the index in the stack, no need to store the pairs.
      Here's the code in cpp:-
      vector calculateSpan(int price[], int n)
      {
      vector v;
      stack s;
      for(int i=0;i

  • @sanchitkumar6626
    @sanchitkumar6626 Год назад

    bhaiya please upload some more videos regarding backtraking ,graph ,tree .Your Teaching style is really great .

  • @yatri6329
    @yatri6329 2 года назад +2

    Can we do this just by storing the index in stack

    • @kirtikhohal3313
      @kirtikhohal3313 2 года назад +2

      yes ofc

    • @kirtikhohal3313
      @kirtikhohal3313 2 года назад +2

      vector calculateSpan(int price[], int n)
      {
      vector v;
      stack s;
      for(int i=0;i

  • @lakshaybansal9597
    @lakshaybansal9597 2 года назад

    Plz continue upload the video this is very helpful

  • @arpitkhanulia7
    @arpitkhanulia7 Год назад +1

    vector calculateSpan(int price[], int n)
    {
    stacks;
    vectorans;
    for(int i=0; i0 and s.top().first price[i] ) ans.push_back( i - s.top().second);
    s.push({price[i],i});
    }
    return ans;
    }

  • @ChetanSingh-zp4ct
    @ChetanSingh-zp4ct 3 года назад +1

    Well had a question, what we are looking for is consecutive smaller elements and that could be equal to the number of times we pop the top element from the Stack so can't we just maintain a count variable and increment it each time we pop the the Stack and by pushing the count in vector we can have the answer

  • @mukulvashishth9974
    @mukulvashishth9974 4 года назад

    Amazing explanation brother @Aditya Verma ...Was looking for a playlist like this !!

  • @fahadisrar2195
    @fahadisrar2195 4 года назад

    You made it look easy to identify the type. Great !!

  • @LokeshSharma-hm5jz
    @LokeshSharma-hm5jz Год назад

    how easy this question is now. Thank you

  • @jawwadakhter5261
    @jawwadakhter5261 4 года назад +1

    Great explanation...brilliant. Thank you for explaining like this.
    last for loop can be neglected if we calculate the NGE during the process,
    <
    l=[10, 4, 5, 90, 120, 80] # span
    ls=[] # Stock
    ans=[] # final answer vector
    for i in range(0,len(l)):
    if len(ls)==0:
    ans.append(1) # as given in the question, if no span.
    elif len(ls)>0 and ls[-1][0]>l[i]:
    ans.append(i-ls[-1][1]) # index-position of NGE
    elif len(ls)>0 and ls[-1][0]0 and ls[-1][0]