Maximum Sum Subarray of size K | Sliding Window

Sdílet
Vložit
  • čas přidán 22. 09. 2020
  • Patreon Link: / adityaverma
    Video Pdf Notes And Code: / 41937811
    Playlist Link: • Sliding Window Algorit...
    Problem Description: practice.geeksforgeeks.org/pr...
    Given an array of integers Arr of size N and a number K. Return the maximum sum of a subarray of size K.
    Example:
    Input:
    N = 4, K = 2
    Arr = [100, 200, 300, 400]
    Output:
    700
    Explanation:
    Arr3 + Arr4 =700,
    which is maximum. .
    ------------------------------------------------------------------------------------------
    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.

Komentáře • 430

  • @MarkDSouza46
    @MarkDSouza46 Před 3 lety +267

    There is no one better than you when it comes to Interview Prep. Please make a playlist on graphs!!!

  • @gyanprakash302
    @gyanprakash302 Před 2 lety +20

    This is the most fun way to learn, glad I found you ! Amazing instructor, teaches like a bestfriend

  • @vasachisenjubean5944
    @vasachisenjubean5944 Před 3 lety +189

    BHAI TREES AND GRAPHS! PLEASE START KARO!😔

  • @settyruthvik6236
    @settyruthvik6236 Před 2 lety +11

    #code in python:
    class Solution:
    def maximumSumSubarray(k,arr):
    i=0
    j=0
    csum=0
    maxi=0
    while j

  • @amritmalviya7414
    @amritmalviya7414 Před rokem +15

    Please come back

  • @rajeshranjan6573
    @rajeshranjan6573 Před 2 lety +88

    Same code as mentioned in the video:
    while(j

  • @dimpleshah6538
    @dimpleshah6538 Před 3 lety +16

    Superb Explanation! Very much helpful to people who cannot afford to pay lakhs and thousands to different coaching institutes. Keep up the good work!

  • @vipergo7827
    @vipergo7827 Před 2 lety +17

    java code ->
    static long maximumSumSubarray(int K, ArrayList Arr,int N){
    // code here
    int s = 0;
    int e = 0;
    long maxSum = Long.MIN_VALUE;
    long sum = 0;
    while(e < N)
    {
    sum=sum+Arr.get(e);
    if(e - s + 1 == K)
    {
    maxSum = Math.max(sum,maxSum);
    sum -= Arr.get(s);
    s++;
    e++;
    }
    else
    {
    e++;
    }
    }
    return maxSum;
    }

  • @prathameshkhadse3481
    @prathameshkhadse3481 Před 2 lety +12

    Thanks Aditya Verma for making these videos, I worked on this and DP playlist religiously for a month and got placed.

    • @abhishekpilla8857
      @abhishekpilla8857 Před 2 lety +2

      Wow that's great!! What is "this" you mean...sliding window?? And where did you get placed?

  • @tombrady7390
    @tombrady7390 Před 3 lety +50

    when I am financially stable i will defiantly support u on Patreon

    • @itsmeakash_
      @itsmeakash_ Před rokem +5

      Update?

    • @tombrady7390
      @tombrady7390 Před rokem +7

      @@itsmeakash_ now I am in Deutsche Bank 😅😅

    • @daayush6654
      @daayush6654 Před rokem +2

      ​@@tombrady7390 bro LinkedIn I'd bata do fir referral bhi de Dena if sahi Lage toh

  • @ncertlinebyline8414
    @ncertlinebyline8414 Před měsícem +1

    Slight correction use "continue"..
    If(j-i+1

  • @jagadeeshp1163
    @jagadeeshp1163 Před 3 lety +9

    Bro working with geeks for geeks and all bookmarked questions I'm try ing to start by all Ur superb concepts thanks for the effort brother love from AP

  • @ShubhamKumar-km8pm
    @ShubhamKumar-km8pm Před rokem +2

    One simple way of code
    First obtain the sum till window
    For(int i=0;i

  • @ankitbhatt5630
    @ankitbhatt5630 Před 2 lety +5

    Great Explanation! Looking forward to learning Trees and Graphs! :)

  • @NotNotNithin
    @NotNotNithin Před 3 lety +5

    My solution in Java:
    a. Using a while loop:
    public static int findMaxSumSubArrayUsingWhile(int k, int[] arr) {
    int maxSum = 0, windowStart = 0, windowEnd = 0, windowSum = 0;
    while(windowEnd < arr.length) {
    windowSum += arr[windowEnd];
    if (windowEnd - windowStart + 1 >= k) {
    maxSum = Math.max(maxSum, windowSum);
    windowSum -= arr[windowStart];
    windowStart++;
    }
    windowEnd++;
    }
    return maxSum;
    }
    b. Using a for loop:
    public static int findMaxSumSubArrayUsing For(int k, int[] arr) {
    int maxSum = 0, windowSum = 0;
    int windowStart = 0;
    for (int windowEnd=0; windowEnd < arr.length; windowEnd++) {
    windowSum += arr[windowEnd];
    if(windowEnd >= k-1) {
    maxSum = Math.max(maxSum, windowSum);
    windowSum -= arr[windowStart];
    windowStart++;
    }
    }
    return maxSum;
    }

  • @Amit-jp7vt
    @Amit-jp7vt Před rokem +3

    Your explaination and clarity of concepts is awesome.
    Here for understanding sliding window algorithm.Tysm.
    Please keep uploading👌.

  • @ranjeetsinghbhati5540
    @ranjeetsinghbhati5540 Před rokem +37

    // Maximum Sum SubArray of size k
    #include
    using namespace std;
    int maxsubarray(int *arr,int size,int k){
    int i=0,j=0, sum=0;
    int maxsum=INT_MIN;
    while(jn>>k;
    int *arr=new int[n];
    for(int i=0;i>arr[i];
    }
    cout

    • @omsatpathy5455
      @omsatpathy5455 Před rokem +1

      bhai ye leetcode me TLE kyun de rha ?

    • @asanitian6218
      @asanitian6218 Před 11 měsíci

      What is this code bro..... it's wrong or Am I wrong... please let me know🙏🙏🙏

    • @rudrajha1002
      @rudrajha1002 Před 9 měsíci

    • @tarunparmar1723
      @tarunparmar1723 Před 9 měsíci

      @@asanitian6218Their require a change in code.
      The max condition will come outside the else condition because if it is inside the else condition it will not store the sum forn first k elements

    • @yash12patre78
      @yash12patre78 Před 6 měsíci

      sum , maxsum ka data type long long kardo
      aur while loop m size ki jagah arr.size() kardo
      for C++;

  • @Iamnoone56
    @Iamnoone56 Před 2 lety +1

    '''
    given an array find the max of sum of all subarrays of size k.
    fixed size window problem.
    '''
    def slidingWindow(nums,k):
    i, j = 0, 0
    maxi = -float("inf")
    currWindowSum = 0
    while j

  • @HimanshuSingh-dk4hr
    @HimanshuSingh-dk4hr Před 2 lety +2

    What I can say. I have no word for your explanation. I am speechless. Thankyou so much❤️

  • @mansigoyal4796
    @mansigoyal4796 Před 3 lety +15

    genius logoin ka smjaane ka trika hi alag hota hai... u r genius. I search each question on youtube as question then space aditya verma

  • @yashmadhogaria7418
    @yashmadhogaria7418 Před 3 lety +5

    Your videos are inculcating interest inside me towards programming

  • @rahulnagwanshi2348
    @rahulnagwanshi2348 Před 2 lety +7

    Small clean code under while loop:
    while j

  • @PRANAVMAPPOLI
    @PRANAVMAPPOLI Před 2 lety +3

    #SimplePython
    Start=end=cnrtsum=maxsum=0
    while(end

  • @heenaagarwal6795
    @heenaagarwal6795 Před 3 lety +49

    alti palti :D :D You're the best CZcamsr all around the world. Making teaching fun and easy. It clearly shows you have a great hold in DS and Algos. Please cover all the topics. Please share your knowledge, the way you are already doing. And I am sure, in no time you will be the greatest teacher of the competitive coding. We all are extremely grateful to you. Thanks a lot :)

    • @Lifeisgood108-33
      @Lifeisgood108-33 Před 2 lety +9

      Aditya bhai, lgta h aapke pyaar me gir gyi bhai 😂😂

    • @JameS00989
      @JameS00989 Před rokem +7

      @@Lifeisgood108-33 Aditya bhai lagta hay iske sath hee bhaag gaye youtube se :D 2 saal se gayeb hay banda

  • @ram9523
    @ram9523 Před 3 lety +2

    Superb ,very well explained .
    Knowing the concept is one thing and explaining it to others in a simple way is great .
    Very helpful

  • @shuvbhowmickbestin
    @shuvbhowmickbestin Před 2 lety +2

    Bhaiya is making videos at 6AM in the morning. Some dedication!

  • @anshumanparida7079
    @anshumanparida7079 Před 20 dny

    After watching 100 of videos finally i found the best one Thanks bro

  • @ankoor
    @ankoor Před 3 lety +2

    Python3:
    k = 3
    A = [2, 3, 5, 2, 9, 7, 1]
    n = len(A)
    i = 0
    j = 0
    total = 0
    maxSum = float('-inf')
    while j < n:
    total += A[j]
    if j - i + 1 < k:
    j += 1
    elif j - i + 1 == k:
    maxSum = max(maxSum, total)
    total -= A[i]
    i += 1
    j += 1
    print(f"Max Sum of {k} consecutive elements: {maxSum}")

  • @339_mehbulislam3
    @339_mehbulislam3 Před 2 lety +4

    i applied this tutorial code on gfg but it isnt accepting my code and showing wrong output while i test the same code in jupyter its working fine

  • @rajbhowmick8575
    @rajbhowmick8575 Před 2 lety +17

    Apart from a class apart teaching, I love his subtle pop culture reference. At 16:37 he says "Humara ek e maksaat hai bhai ..*pauses*, badlaa nahi lena hai" ~ Gangs of Wasseypur. Like Netflix, I think we can binge watch Aditya's playlist anytime. Fun and learning is just his forte. @Aditya - A session on Trees and Graphs would be of great help I think. Thanks again for all the help !

  • @shubhamlakhotia1400
    @shubhamlakhotia1400 Před 3 lety +10

    bhai when will you going to upload new video , it almost been a month now

  • @priyanshkumariitd
    @priyanshkumariitd Před 8 měsíci +2

    An edge case can be -
    if ( k > arr.size()){
    return false;
    }
    Such a subarray is impossible

  • @nadimakhtar97
    @nadimakhtar97 Před 3 lety +1

    You are great. please complete this series soon.

  • @yashbajoria6958
    @yashbajoria6958 Před 2 lety

    I think this is the best explanation for me.

  • @jaishriharivishnu
    @jaishriharivishnu Před měsícem

    initially I fond sliding window a bit challenging, and was stuck at the case where window size==1 , i.e i==j.... now i have got a solution for it, use this template and all the questions will be solved
    ws=0;
    for(we=0; we < size of array; we++){
    (1)[take the element]
    (2) while loop ( make sure you put ws

  • @onkarpreetsingh1648
    @onkarpreetsingh1648 Před 3 lety +16

    a request to start graphs after it

  • @chandankrjha
    @chandankrjha Před 3 lety +4

    Which software is used for the notes?

  • @thefizzshow
    @thefizzshow Před 2 lety

    Beautifully Explained...

  • @tamishverma2261
    @tamishverma2261 Před 3 lety +3

    Thanks a lot simple and effective way

  • @chanchalverma6307
    @chanchalverma6307 Před 2 lety

    great teaching skill man

  • @rtn3756
    @rtn3756 Před 9 měsíci +2

    class Solution{
    static long maximumSumSubarray(int K, ArrayList Arr,int N){
    long sum = 0;
    long max = Integer.MIN_VALUE;
    int i = 0;
    int j = 0;
    while(j

  • @omerbakhtiar5446
    @omerbakhtiar5446 Před rokem

    very well explained, keep up the good work
    😃😃

  • @aditim4374
    @aditim4374 Před 3 lety +2

    Hi can you please set up some way to use Debit card on your patreon page or give any other site where your notes are accessible? I really want to pay but I do not have a credit card and paypal doesn't work

  • @PrinceSharma-jg2mh
    @PrinceSharma-jg2mh Před 3 lety

    sir where we have to put sum += arr[j]; in f loop or else if loop

  • @pratika-prakhar
    @pratika-prakhar Před 3 měsíci

    Your Recursion and Backtracking Playlist awesome 👍

  • @DebanjanGuhaThakurata

    Great Explanation Sir..

  • @aartibhatnagar3989
    @aartibhatnagar3989 Před rokem +1

    Baiyya you are awesome!!! 🔥
    int main(){
    int m, n;
    cin>>m>>n;
    vector a(m, 0);
    a[n-1] = 1;
    int sum=0;
    int i=0, j=0;
    while( j

  • @dydx3741
    @dydx3741 Před 2 měsíci

    start_idx = 0
    end_idx = 0
    sum = 0
    max_sum = 0
    window_size = 3
    array = [-1 , -2, 10, 5 ]
    while( end_idx < len(array) ):
    sum = sum + array[ end_idx ]
    if ( end_idx - star_idx + 1 < window_size ):
    end_idx += 1
    else:
    max_sum = max( max_sum, sum)
    end_idx += 1
    sum = sum - array[ start_idx ]
    start_idx += 1
    print(max_sum)

  • @jitinroy2246
    @jitinroy2246 Před 2 lety +5

    JAVA CODE************
    import java.util.Arrays;
    import java.lang.*;
    public class Main
    {
    public static int window(int[] arr, int k){
    int i=0,j=0;
    int maxcurr=0;
    int maxsum=Integer.MIN_VALUE;
    while(j

  • @djshah6370
    @djshah6370 Před 2 lety

    very great explain...thank you

  • @04.nehalsingh12
    @04.nehalsingh12 Před 2 lety

    awesome explanation sir

  • @bhargavsai2449
    @bhargavsai2449 Před 3 lety +1

    Wonderful brother.

  • @vibhutimaheshwari7350
    @vibhutimaheshwari7350 Před 6 měsíci

    @Aditya The Patreon link isnt allowing access to code without payment!!

  • @ganeshjaggineni4097
    @ganeshjaggineni4097 Před měsícem

    NICE SUPER EXCELLENT MOTIVATED

  • @nikitajaiswal9112
    @nikitajaiswal9112 Před 2 lety

    class Solution:
    def helper(self,arr,k):
    i,j,s,mx=0,0,0,0
    while j

  • @rahuldwivedi4758
    @rahuldwivedi4758 Před 6 měsíci

    Don’t think j-I+1 == k check is required. A simple check of j

  • @CosmosHole
    @CosmosHole Před 4 měsíci

    Thank you so much for making such video

  • @saitejavaddepalli3400
    @saitejavaddepalli3400 Před 2 lety +4

    Rather simple implementation in java:
    static int maximumSumSubarray(int k, ArrayList arr,int N){
    // sum it upto k
    int sum = 0;
    for(int i = 0; i < k; i++){
    sum += arr.get(i);
    }
    // create a variable max and assign it with sum
    int max = sum;
    // create a pointer that point to 1st index
    int j = 0;
    // include kth index and remove jth index
    for(int i = k; i < N; i++, j++){
    sum = sum + arr.get(i) - arr.get(j);
    max = Math.max(sum, max);
    }
    // return the maximum
    return max;
    }

  • @skimtiazali2001
    @skimtiazali2001 Před 3 lety

    you are like superman of coding dude!

  • @herculean6748
    @herculean6748 Před rokem +1

    Sliding window application 😄🔥

  • @subhankarhotta7094
    @subhankarhotta7094 Před 2 lety +1

    I think we could also solve it without using a ptr for i right? We could simply use the window size and j to find out the first element of the prev window to be discarded everytime in the sum.

  • @philosphize
    @philosphize Před rokem +1

    Man where are you.
    Thanks for such great tutorial
    Please start doing CZcams again

  • @subhajitdas1882
    @subhajitdas1882 Před rokem

    Very well explained.

  • @yashkhatwani3198
    @yashkhatwani3198 Před 2 lety

    Awesome. Thank you bhaiya.

  • @anchalmehandiratta8497

    Nice explanation🙌

  • @mohit84604
    @mohit84604 Před rokem +1

    javascript solution :-
    let array = [100,200,300,400]
    let k = 2
    function solve(array,k) {
    debugger
    let sum = 0
    let max = 0
    let i = 0
    let j = 0
    while (j < array.length) {
    sum += array[j]
    if(j - i + 1

  • @cse-b-167udoishankargogoi2

    can we use kadanes algo for this

  • @prithvirajpatil7388
    @prithvirajpatil7388 Před 2 lety

    superb explanation

  • @VanshSharma-ce6km
    @VanshSharma-ce6km Před rokem

    long sum=0 ,ans=INT_MIN;
    int l =0 , i=0;
    while(i

  • @prashantmaurya9635
    @prashantmaurya9635 Před 3 lety

    Nicely coded 👍

  • @luckymishra5207
    @luckymishra5207 Před rokem +3

    long maximumSumSubarray(int K, vector &Arr , int N){
    int i=0,j=0;
    long ans=INT_MIN;
    long sum=0;
    while(j

  • @reddykishore2496
    @reddykishore2496 Před 3 lety +3

    Bro explain combination of prefixsum , sliding window and binary search searching problems

  • @teenagepanda8972
    @teenagepanda8972 Před 3 lety +1

    Bhai you are a legend 💯💯

  • @ritiksrivastava9069
    @ritiksrivastava9069 Před 2 lety

    finally sab kuch samajh aagya h sir.

  • @alphagaming5432
    @alphagaming5432 Před 4 měsíci

    thank you so much Bhaiya

  • @sudhadevi6692
    @sudhadevi6692 Před rokem +1

    Thx bhaiya❤

  • @shankysays
    @shankysays Před 3 lety +1

    Is it similar to kadane algorithm?

  • @pragatishrivas7144
    @pragatishrivas7144 Před rokem

    great explanation

  • @jr_jeet
    @jr_jeet Před rokem

    if we use for loop instead of while than it will be ok ??

  • @ramankumarlal6915
    @ramankumarlal6915 Před 3 lety

    Thank You

  • @sibasish.tripathy
    @sibasish.tripathy Před 2 lety +3

    during this one video of lecture i am distracted 10 times through ads

  • @talosrobo9435
    @talosrobo9435 Před rokem

    awsmm explanation !!!! thanxaaa ❤❤❤❤

  • @techykush7192
    @techykush7192 Před 3 lety +2

    bhaiya plzzz start graph series 👏👏👏

  • @The_Shubham_Soni
    @The_Shubham_Soni Před rokem

    great explanation!!

  • @ShivamGupta-cx3hy
    @ShivamGupta-cx3hy Před 3 lety +3

    Here is the code of above explaination But it is not accepting for multiple test cases
    Can anyone tell why?
    int maximumSumSubarray(int K, vector &A , int N){
    // code here
    int i=0;
    int j=0;
    int sum=0;
    int maxsum=INT_MIN;
    while(j

  • @kiratsinghsaluja9123
    @kiratsinghsaluja9123 Před 6 měsíci

    Thanks Sir

  • @abhikrity9758
    @abhikrity9758 Před 2 lety

    Good way of explanation. Thought of watching complete series, but it's too lengthy an repeatative.

  • @ankushladani496
    @ankushladani496 Před 8 měsíci

    Thanks bhaiya...❤🎉

  • @amolnagotkar3037
    @amolnagotkar3037 Před 2 lety

    thnx for this video

  • @ajitkerle6607
    @ajitkerle6607 Před rokem

    He has good knowledge

  • @surajsharma-1554
    @surajsharma-1554 Před 4 měsíci +1

    C++ Code:
    long maximumSumSubarray(int K, vector &Arr , int N){
    // code here
    long ans = INT_MIN;
    long sum = 0;
    int i=0,j=0;
    while(j

  • @sauravthakur2915
    @sauravthakur2915 Před rokem +1

    5:55 " ghar baithe bana sakta hai " 😂😂

  • @pahaljain9209
    @pahaljain9209 Před rokem

    Well Explained

  • @k.chandanapriya4004
    @k.chandanapriya4004 Před 3 lety +13

    Agli video kab ayegi? Waiting eagerly 😭😭 please make videos on graphs

  • @farzadkhan3813
    @farzadkhan3813 Před 11 měsíci

    long maxSum = Integer.MIN_VALUE; // why not 0? To handle -ve nums
    long sum = 0;
    int i = 0; // start index
    int j = 0; // end index
    while(j < N) { // iterating over all the elements
    sum += Arr.get(j);
    if(j-i+1 == K) {
    maxSum = Math.max(sum, maxSum);
    sum -= Arr.get(i++);
    }
    j++;
    }
    return maxSum;

  • @TECHINFOS
    @TECHINFOS Před 3 lety +37

    #include
    using namespace std;
    int main()
    {int t;
    cin>>t;
    while(t--)
    {//max of subarray of size k
    int n,k;
    cin>>n>>k;//size of array and subarray
    int a[n];
    vectorv;
    for(int i=0;i>a[i];
    }
    int i=0,j=0,sum=0;
    while(j

    • @utkarshgautam1940
      @utkarshgautam1940 Před 3 lety +8

      love u bro ,this dumb havent provided the code

    • @skandhakarlamangal5204
      @skandhakarlamangal5204 Před 3 lety +21

      @@utkarshgautam1940 I think he provided the required explanation to arrive at the code. If you are unable to follow, you must reconsider the definition of dumb in your head.

    • @soniamalik4929
      @soniamalik4929 Před 2 lety +1

      @@utkarshgautam1940 Phle tolo,fir bolo....Watch some genius's lecture...not Dumb's lecture then.Have guts to arrive at code by yourself..kB tk spoonfeed krega tumhe koi.bro

    • @utkarshgautam1940
      @utkarshgautam1940 Před 2 lety +2

      @@soniamalik4929 when u revising this just before ur interview ,u make psedo code ,now u need to check then we need the code, that's what I mean

    • @soniamalik4929
      @soniamalik4929 Před 2 lety +1

      @@utkarshgautam1940 oh Utkarsh got your point now!!Good luck!!

  • @gocrazy6177
    @gocrazy6177 Před rokem

    Dammmm nice explanation !

  • @shubham7668
    @shubham7668 Před 2 lety +1

    5:50 Aaram se ghar baith ke bana sakta hai koi bhi banda 😂😂
    Bhaiya aap ques ki hi baat kar rahe ho na? 😂

  • @yashpatel-dx8wr
    @yashpatel-dx8wr Před 3 lety +4

    it's easy if we are using deque with fixed size.

  • @Sinha78685
    @Sinha78685 Před rokem

    Can anyone suggest me other important leetcode algorithms like Sliding window?