Maximum Sum Subarray of size K | Sliding Window
HTML-код
- Опубликовано: 11 сен 2024
- Patreon Link: / adityaverma
Video Pdf Notes And Code: / 41937811
Playlist Link: • Sliding Window Algorit...
Problem Description: practice.geeks...
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.
There is no one better than you when it comes to Interview Prep. Please make a playlist on graphs!!!
yessss bruh!!!!
Update
@@Yashkumar-fn1jw where?
Yes plz.
Same code as mentioned in the video:
while(j
isn,t is showing runtime error.
Nope it's working fine just for the last edge case described by him
@@a.srivas6741
if(N
@@a.srivas6741 Check for long range edge cases
long maxSum=0;
for(int i=0;i
BHAI TREES AND GRAPHS! PLEASE START KARO!😔
+1
Graph series needed
+1
+1
khud se pdh le bhai easy hai. yaad krta hai kya aditya ki videos dekh k? :p
when I am financially stable i will defiantly support u on Patreon
Update?
@@itsmeakash_ now I am in Deutsche Bank 😅😅
@@tombrady7390 bro LinkedIn I'd bata do fir referral bhi de Dena if sahi Lage toh
@@tombrady7390 linked in?
@@daayush6654 update?
Thanks Aditya Verma for making these videos, I worked on this and DP playlist religiously for a month and got placed.
Wow that's great!! What is "this" you mean...sliding window?? And where did you get placed?
Bhai ek mahine ki padhayi se job miljaati hai?
This is the most fun way to learn, glad I found you ! Amazing instructor, teaches like a bestfriend
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 !
was searching for this comment
@@anshmishra3066 worked so hard
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
Small clean code under while loop:
while j
Superb Explanation! Very much helpful to people who cannot afford to pay lakhs and thousands to different coaching institutes. Keep up the good work!
#code in python:
class Solution:
def maximumSumSubarray(k,arr):
i=0
j=0
csum=0
maxi=0
while j
Slight correction use "continue"..
If(j-i+1
alti palti :D :D You're the best RUclipsr 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 :)
Aditya bhai, lgta h aapke pyaar me gir gyi bhai 😂😂
@@Lifeisgood108-33 Aditya bhai lagta hay iske sath hee bhaag gaye youtube se :D 2 saal se gayeb hay banda
One simple way of code
First obtain the sum till window
For(int i=0;i
You can also go with
Int sum=0;
for (int i=0; i
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
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;
}
this code gives tle
'''
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
Please come back
#SimplePython
Start=end=cnrtsum=maxsum=0
while(end
Concise implementation:
int maximumSumSubarray(vector &Arr , int N, int K){
int i = 0, j = 0, sum = 0, max_el = INT_MIN;
while (j < N) {
sum += Arr[j++];
if (j - i == K) {
max_el = max(max_el, sum);
sum -= Arr[i++];
}
}
return max_el;
}
int i=0,j=0;
int sum =0;
int mx = INT_MIN;
while(j
@@xplorewithdeba7869 in else if you are not increasing j
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}")
Thanks
Bro can u provide all python programs pf remaining questions
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;
}
// 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
bhai ye leetcode me TLE kyun de rha ?
What is this code bro..... it's wrong or Am I wrong... please let me know🙏🙏🙏
❤
@@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
sum , maxsum ka data type long long kardo
aur while loop m size ki jagah arr.size() kardo
for C++;
Don’t think j-I+1 == k check is required. A simple check of j
Your explaination and clarity of concepts is awesome.
Here for understanding sliding window algorithm.Tysm.
Please keep uploading👌.
Your videos are inculcating interest inside me towards programming
What I can say. I have no word for your explanation. I am speechless. Thankyou so much❤️
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
Bhaiya is making videos at 6AM in the morning. Some dedication!
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;
}
Great Explanation! Looking forward to learning Trees and Graphs! :)
5:55 " ghar baithe bana sakta hai " 😂😂
a request to start graphs after it
bhai when will you going to upload new video , it almost been a month now
After watching 100 of videos finally i found the best one Thanks bro
Bhaiya,I started learning java post lockdown,tried to prepare myself for placement when summer vacation started.Luckily I came across ur channel.I have been here since ur first video.Just wanted to thanku for everything.Being from non cs I didn't expect me doing well..but luckily efforts paid off,thanks to ur videos..I got placed in General Electric software profile.Ur videos are unparalleled and unmatched.I owe u a lot❤️
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
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
Man where are you.
Thanks for such great tutorial
Please start doing RUclips again
class Solution:
def helper(self,arr,k):
i,j,s,mx=0,0,0,0
while j
Agli video kab ayegi? Waiting eagerly 😭😭 please make videos on graphs
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)
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
what an explanation ! made it super easy for me . thanks a lot
Sliding window application 😄🔥
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
5:50 Aaram se ghar baith ke bana sakta hai koi bhi banda 😂😂
Bhaiya aap ques ki hi baat kar rahe ho na? 😂
Once you recommended jenny's channel and yes i watch her daily.😎😂
Haan, Unka explanation bhi kaafi badiya hota hai
@@ansar2137really not only explanation everything lol
Is that even an explanation? That's Theory which looks nice only on end SEM college paper lol
@@bhavyamalviya8364 surely not but im talking about her she is cute
@@ashutoshkumardwivedi3949 Placement ka padh le bhai 😂 College professor hain Jenny mam.
Superb ,very well explained .
Knowing the concept is one thing and explaining it to others in a simple way is great .
Very helpful
long maximumSumSubarray(int K, vector &Arr , int N){
int i=0,j=0;
long ans=INT_MIN;
long sum=0;
while(j
is this question available on leetcode
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
#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
love u bro ,this dumb havent provided the code
@@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.
@@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
@@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
@@utkarshgautam1940 oh Utkarsh got your point now!!Good luck!!
Thx bhaiya❤
BHAI TREES AND GRAPHS! PLEASE START KARO
@aditya verma
An edge case can be -
if ( k > arr.size()){
return false;
}
Such a subarray is impossible
Bhaiya ek baar strings ki series bna do, strings bhut confuse krti hai. Placement hote hi party dunga aapko , aapne video dekhne k bad DSA ka drr khtm hua h.
Bayya upload videos regularly ....3 videos per week ...at least...
here is the code discussed in the lecture:
#include
#include
using namespace std;
using namespace std;
long long maximumSumSubarray(int k, vector &a, int n){
int i = 0, j = 0;
long long sum = 0;
while(j-i+1 n >> k;
vector a(n);
for(long i=0;i> a[i];
}
cout
long sum=0 ,ans=INT_MIN;
int l =0 , i=0;
while(i
during this one video of lecture i am distracted 10 times through ads
Your Recursion and Backtracking Playlist awesome 👍
Can you make a video explaining stock buy and sell and its variations? P.S. You helped me a lot in understanding DP, great work!
Check Out Pepcoding For that 6 problems covered
Which software is used for the notes?
bhaiya plzzz start graph series 👏👏👏
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;
Thanks a lot simple and effective way
Java Solution:
-----------------------
public static int findMaxSum (int [] array, int k) {
int i =0, j = 0;
int max = 0, sum = 0;
while (j < array.length) {
sum = sum + array[j];
if (j-i+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
code:
int i=0;int j=0;
long sum=0;long maxi=-1e9;
while(j
it's easy if we are using deque with fixed size.
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
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
class Solution{
static long maximumSumSubarray(int k, ArrayList nums,int n){
// code here
long sum = 0;
long res = 0;
int i=0;
for(i=0; i
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.
True!
long long int maximumSumSubarray(int K, vector &Arr , int N)
{
long long int res = 0;
long long int sum = 0;
for(int i = 0; i < K - 1; i++) sum += Arr[i];
for (int i = K - 1; i
Bro explain combination of prefixsum , sliding window and binary search searching problems
Why this method isn't used??
int sum=0;
for(int i=0;i
C++ code:
long maximumSumSubarray(int K, vector &Arr , int N){
long i = 0;
long j= 0;
long sum = 0;
long maxSum = INT_MIN;
while(j < N) {
sum += Arr[j];
if(j-i+1 < K) {
j++;
}
else if(j-i+1 == K) {
maxSum = max(maxSum, sum);
sum -= Arr[i];
i++;
j++;
}
}
return maxSum;
}
You are great. please complete this series soon.
Bhaiya sliding window ka 4th video apne private kr rakha h .... I m dying to learn more from you ❤️❤️❤️ please upload videos.
long maximumSumSubarray(int k, vector &arr , int n){
// code here
long long int sum=0;
for(int i=0;i
class Solution {
maximumSumSubarray(K, Arr, N) {
//console.log(Arr)
let sum = 0;
let i=0;
let j=0;
let max = 0;
if(K>N){
return -1
}
while(j
Good way of explanation. Thought of watching complete series, but it's too lengthy an repeatative.
This is the code for this video in C++
#include
using namespace std;
int main() {
vector v = {2, 5, 1, 8, 2, 9, 1};
// find the subarray of size 3 whose sum is maximum
int sum = 0, maxi = INT_MIN, k = 3;
int i = 0, j = 0;
while(j < v.size()) {
// if window size is not equal to k, then increase the window size
if (j - i + 1 < k) {
sum += v[j];
j++;
} else if (j - i + 1 == k) {
sum = sum + v[j];
maxi = max(maxi, sum);
sum = sum - v[i];
i++;
j++;
}
}
cout
easy to understand code than aditya verma time O(n) space O(1)
long maximumSumSubarray(int k, vector &arr , int n){
long int maxSum=INT_MIN;
long int sum=0;
for(int i=0;i
can you enable english subtitles for tamil people
I think this is the best explanation for me.
static int findMaxSubArray(int a[], int k) {
int i = 0, j = 0;
int sum = 0;
int max = Integer.MIN_VALUE;
while (j < a.length) {
sum = sum + a[j];
if (j - i + 1 >= k) {
max = Math.max(sum, max);
sum = sum - a[i];
i++;
}
j++;
}
return max;
}
bhai Game of thrones se bi Jayda Maja ata hai tera videos.
you are very good instructor but beginners find very hard to understand , write code in proper manner
My Java Code -
public class MyClass {
public static void main(String args[]) {
int arr[]={1, 4, 2, 10, 23, 3, 1, 0, 20};
int k=4;
int i=0;
int j=0;
int sum=0;
int ans=Integer.MIN_VALUE;
int size=arr.length;
while(j
NICE SUPER EXCELLENT MOTIVATED
Beautifully Explained...
16:30 ek hi maksad hai ---> Badla nhi lena hai 😂😂😂😂
14:00 yeah, i was approaching like that, fixing the window at the start
Are you not going to make any videos further? Your videos are the best
Great Explanation Sir..
Bhai you are a legend 💯💯
private static int maxSum2(int[] nums, int windowSize) {
int i=0;
int j=0;
int maxSum = 0;
int sum = 0;
while(j< nums.length){
sum += nums[j];
if((j - i + 1) < windowSize){
j++;
continue;
}else if((j - i + 1) == windowSize){
maxSum = Math.max(sum, maxSum);
}
sum = sum - nums[i];
i++;j++;
}
return maxSum;
}
Apun ka ek hee maksad hai "badla" nhi lena🤣