L12. Candy | Slope Approach Intuition Based

  Рет қаралды 48,056

take U forward

take U forward

Күн бұрын

Find problem link, notes under Step 12: takeuforward.o...
Follow me on socials: linktr.ee/take...

Пікірлер: 92
@jay3952
@jay3952 7 күн бұрын
15:31 "if you don't know it you will not be able to think about it in an interview" best advise ever
@frand1956
@frand1956 Ай бұрын
For those who are facing errors class Solution { public: int candy(vector& ratings) { int n=ratings.size(); int i=1; int sum=1; while(i
@Nikhil-jd2up
@Nikhil-jd2up Ай бұрын
7 is not being added in the video as down is being incremented after adding it to sum so the loop stops when down=6 is added to sum and then it is incremented to 7
@VinothiniAnabayan
@VinothiniAnabayan 16 күн бұрын
i understood it now after a long video, your command only helped me
@venkatmalviya2421
@venkatmalviya2421 12 күн бұрын
Loved the last approach. I have faced various questions where I wanted to utilise the slope insight but was unable to implement. Thanks for giving me this tool.
@ayaaniqbal3531
@ayaaniqbal3531 8 ай бұрын
The last approach was mind Blowing .From my own i could not have imagined this approach.Thank you striver for this amazing video😄
@abhimanyuambastha2595
@abhimanyuambastha2595 7 ай бұрын
All the solutions remove the minimum of down and peak from the sum without properly explaining the reason. Only striver's video explains exactly the reason and also how he came to it. This is the stuff that passes you interviews when you understand how to come to the solution. Just everybody copying a solution without understanding, in interviews you will be completely lost as to what to do and why to do. Thank you for the wonderful explanation
@manthansingh6302
@manthansingh6302 8 ай бұрын
In the 2nd approach, you also have to update the right's value in else case. Btw amazing explanation, loved the optimized approach.
@Gamershettyprateek
@Gamershettyprateek 2 күн бұрын
function candy(ratings: number[]): number { let n = ratings.length; let leftN = Array(n).fill(1); for(let i = 1; i < n; i++) { if(ratings[i]> ratings[i-1]){ leftN[i] = leftN[i-1] + 1; } else { leftN[i] = 1; } } let sum = Math.max(leftN[n-1],1); let cur = 1; for(let i = n-2; i >=0; i--) { if(ratings[i]> ratings[i+1]){ cur = cur + 1; } else { cur = 1; } sum += Math.max(leftN[i],cur); } return sum; };
@ankurdas1477
@ankurdas1477 4 ай бұрын
Correct code of the optimal approach int sum=1, i=1, n=ratings.size(); while(i
@shreshthkaushik-hu8bz
@shreshthkaushik-hu8bz 3 ай бұрын
Or you can do this, if we want to avoid doing the down++; after the downward trend/slope. Keeps the code more consistent with the upwards trend. Just add the downward_peak to total/sum before incrementing. # Create a variable to get the length of the ratings array # and a variable to keep track of the index we are on. # We will start with an index of 1 since we want to compare # values from one index before (index - 1) index, length_of_ratings = 1, len(ratings) # Create a variable to keep track of the number # of candies we have given to each children # give the first child, one candy number_of_candies = 1 # Iterate through the ratings array till the end while index < length_of_ratings: # Case-1: Where the neighbor child has same rating if ratings[index] == ratings[index - 1]: # As per requirement number-1 in the question # Give them just one candy number_of_candies += 1 index += 1 # Case-2: Where the child has greater rating than its previous neighbor # We create a variable called "upward_peak" to track the highest amount # of candy we gave while Case-2 is true upward_peak = 1 while index < length_of_ratings and ratings[index] > ratings[index - 1]: upward_peak += 1 number_of_candies += upward_peak index += 1 # Case-3: Where the child has smaller rating than its previous neighbor # We create a variable called "downward_peak" to track the highest amount # of candy we gave while Case-3 is true downward_peak = 1 while index < length_of_ratings and ratings[index] < ratings[index - 1]: number_of_candies += downward_peak downward_peak += 1 index += 1 # At this point of the code, it is possible that our "downward_peak" # was greater than the upward_peak, that means we need to add higher of those peaks # and since we already added one part of it in sum, we will add the difference if downward_peak > upward_peak: number_of_candies += (downward_peak - upward_peak) # Return the summation of the candies given return number_of_candies
@_Dream_Dive_
@_Dream_Dive_ 2 ай бұрын
if (down >= peak) { sum += (down - peak + 1); // Add the difference here, removing the need for `down++`. }
@rohandevaki4349
@rohandevaki4349 24 күн бұрын
at 13:33 , you missed right =1; at else curr=1 . this approach is simple and intuitive, thankyou
@Hari-xq1qq
@Hari-xq1qq 7 ай бұрын
Best video in entire DSA
@yuvrajbhardawaj2045
@yuvrajbhardawaj2045 7 ай бұрын
Small correction in O(2N) solution static int minCandy(int n, int ratings[]) { // code here //Brute Force // int left[] = new int[N]; // int right[] = new int[N]; // left[0]=1; //since we start from left the 1st element will be 1 // right[N-1]=1; //since we start from right the right[N-1] is 1 // for(int i=1;iratings[i-1]) // left[i]=left[i-1]+1; // else // left[i]=1; // } // for(int j=N-2;j>=0;j--){ // if(ratings[j]>ratings[j+1]) // right[j]=right[j+1]+1; // else // right[j]=1; // } // int sum=0; // for(int k=0;k=0;i--){ if(ratings[i]>ratings[i+1]) curr=right+1; else curr=1; right=curr; // right is updated outside if else sum+=Math.max(left[i],curr); } return sum; }
@anshumansingh6316
@anshumansingh6316 6 ай бұрын
we can avoid one variable itself in better solution, instead of assigning curr to right, we can use curr only
@Pw_Unfiltered
@Pw_Unfiltered 17 күн бұрын
class Solution { public: int candy(vector& arr) { int n = arr.size(); if (n == 1) return 1; int sum = 1; // Start with 1 candy for the first child int up = 0; // Length of the last increasing sequence int down = 0; // Length of the last decreasing sequence int peak = 0; // Peak of the last increasing sequence for (int i = 1; i < n; ++i) { if (arr[i] > arr[i - 1]) { // Upward slope up++; peak = up; // Update peak down = 0; // Reset downward slope sum += up + 1; // Add candies for this child } else if (arr[i] < arr[i - 1]) { // Downward slope down++; up = 0; // Reset upward slope sum += down; // Add candies for downward slope if (down > peak) { // Adjust if downward slope is longer than the peak sum++; } } else { // Flat slope (arr[i] == arr[i - 1]) up = 0; down = 0; peak = 0; sum += 1; // Each child gets at least 1 candy } } return sum; } };
@Sangi-sj2dy
@Sangi-sj2dy 7 ай бұрын
Your videos makes my day awesome
@suhasherle7350
@suhasherle7350 3 ай бұрын
int candy(vector& ratings) { int n = ratings.size(); int cnt = 0; vector res(n,1); for(int i = 1; i < n; i++){ if(ratings[i] > ratings[i-1]){ res[i] = res[i-1] + 1; } } cnt += res[n-1]; cout ratings[i+1]){ res[i] = max(res[i+1] + 1, res[i]); } cnt += res[i]; } return cnt; } the O(2N) approach
@SibiRanganathL
@SibiRanganathL 4 ай бұрын
bhai the slow intuition just blew my mind
@shivamthapliyal4818
@shivamthapliyal4818 8 ай бұрын
striver can you please increase the frequency of uploading videos. It will help the students like me . I appreciate your work a lot. Thankyou
@prain_8989
@prain_8989 8 ай бұрын
Bro can i start this playlist after learning python
@vrajpatel9259
@vrajpatel9259 7 ай бұрын
@@prain_8989 yes, you just need to learn basics of python.. the syntax.. that's all.. than as you will follow this playlist you will catch the remaining things.. but in python dsa is not as hard as compared to c++. if you are not in final year than you can do c++ cuz c++ is way better as it will improve your problem solving skills
@apmotivationakashparmar722
@apmotivationakashparmar722 4 ай бұрын
Great Explaination.
@Dsa_kabaap
@Dsa_kabaap 8 ай бұрын
Sir please start making videos on strings and stacks
@securelyinsaycure
@securelyinsaycure 5 ай бұрын
Thank you Thank you Thank you
@nagasrikuncharapu3736
@nagasrikuncharapu3736 7 ай бұрын
1x feels like 0.5x to me after listening to all of his classes in 2.5x 😆
@TechieClasher
@TechieClasher 7 ай бұрын
suprisingly i came up with most optimal approach by myself, but did not come up with naive solution. IDK my intuition is really good nowadays but , implementation sucks and couldnt code it, any suggestions how to improve implementation skills ? (i can understand others solutions easily but cant code it myself even after knowing intution)
@ayushivishwakarma9101
@ayushivishwakarma9101 7 ай бұрын
same is the case with me if you get a solution to it pls share it.
@AmandeepSingh-rd6ql
@AmandeepSingh-rd6ql 7 ай бұрын
Same problem
@RISHABHKUMAR-w5z
@RISHABHKUMAR-w5z 7 ай бұрын
same problem bro
@SondiPremSmith
@SondiPremSmith 7 ай бұрын
just go by 30min implementation task if do not get the approach see the hints do it for 10 to 20min roughly dude if you still stuck with the problems see the approach practice repeat 🔁........>>>>>> The one who gave up may fail, but the one who loop(tried and failed) will never loose. so never stop every failed problem teach you something learn it evolve .....
@sushmi6400
@sushmi6400 6 ай бұрын
@@TechieClasher hey how many months does it took for you to complete the entire a to z course and how many hours you used to allocate for it
@Gamershettyprateek
@Gamershettyprateek 2 күн бұрын
2nd Approach Code in JS TC - O(2n) SC - O(n) function candy(ratings: number[]): number { let n = ratings.length; let leftN = Array(n).fill(1); for(let i = 1; i < n; i++) { if(ratings[i]> ratings[i-1]){ leftN[i] = leftN[i-1] + 1; } else { leftN[i] = 1; } } let sum = Math.max(leftN[n-1],1); let cur = 1; for(let i = n-2; i >=0; i--) { if(ratings[i]> ratings[i+1]){ cur = cur + 1; } else { cur = 1; } sum += Math.max(leftN[i],cur); } return sum; };
@karthikkrishna1837
@karthikkrishna1837 3 ай бұрын
Whats the intuition behind the two way traversal approach. I remember seeing a couple of paranthesis string problems etc also done by this approach but I dont get the logic behind it. How does this work?
@Bhavnachouhan-tm5yt
@Bhavnachouhan-tm5yt 5 ай бұрын
Thank you bhaiya ❤
@iamnoob7593
@iamnoob7593 7 ай бұрын
SUPERB STRIVER SIR.
@studysprintz
@studysprintz 23 күн бұрын
at 6:05 if are just considering left neighbors even then 4 has higher rating than 0 and its still getting equal candies as 0 . how?? can someone explain??
@thoughtsofkrishna8963
@thoughtsofkrishna8963 7 ай бұрын
What is the optimal approach if they asked for the resultant array ???
@anuragsekhri2315
@anuragsekhri2315 5 ай бұрын
Well explained
@instinct1098
@instinct1098 8 ай бұрын
Slope Approach is amazing
@AtulRawat-sf2lw
@AtulRawat-sf2lw 8 ай бұрын
hello sir i am in going to be in 1st year can i do strivers dsa course from youtube without learning C++ separately as i have done C please reply...
@doremon81072
@doremon81072 8 ай бұрын
@@AtulRawat-sf2lw you have enough time, first try to learn any programmin language then start striver's dsa it will be easy, else you will stuck in many things. learn the basicof c++ and oops then start striver's sheet. Best wishes
@AtulRawat-sf2lw
@AtulRawat-sf2lw 8 ай бұрын
@@doremon81072 sir striver playlist has some c++ vedio are they enough or separately i should do c++...
@ravenin9612
@ravenin9612 8 ай бұрын
​@@doremon81072Bro I'm in 4th year, I only know basics of Java and no idea on dsa. Can I start now and be able to get a job by the time I complete my final year?
@ravenin9612
@ravenin9612 8 ай бұрын
​@@doremon81072and is this playlist good? But why is there a lot of videos in this playlist???
@AdityaKumar-be7hx
@AdityaKumar-be7hx 7 ай бұрын
Using better variable naming for 2nd appraoch class Solution { public: int candy(vector& ratings) { int n=ratings.size(); vector allocation(n, 1); for(int i=1; iratings[i+1]){ allocation[i]=max(allocation[i], allocation[i+1]+1); } } int candy=0; for(int a:allocation){ candy = candy + a; } return candy; } };
@neelulalchandani7429
@neelulalchandani7429 6 ай бұрын
understoooooooooooooooooooooood
@storm19019
@storm19019 7 ай бұрын
Is it patented approach
@ujjwalverma8663
@ujjwalverma8663 5 ай бұрын
class Solution { public int candy(int[] ratings) { int sum = 1; // Initial candy count for the first child int n = ratings.length; // Number of children int i = 1; // Start from the second child while(i < n) { if (ratings[i] == ratings[i - 1]) { sum++; // Equal ratings, give 1 candy i++; continue; } int peak = 1; // Start with 1 candy for the "uphill" sequence while (i < n && ratings[i] > ratings[i - 1]) { peak++; // Increment candy count as ratings increase sum += peak; // Add to total sum i++; } int down = 1; // Start with 1 candy for the "downhill" sequence while (i < n && ratings[i] < ratings[i - 1]) { down++; // Increment candy count as ratings decrease sum += down; // Add to total sum i++; } // Adjust sum if the peak candy count was greater than the downhill candy count if (peak > down) { sum += peak - down; } } return sum; // Return the total number of candies needed } } My this code is giving wrong answer , can anyone help me out Input ratings = [1,0,2] Output 6 Expected 5
@fazilshafi8083
@fazilshafi8083 5 ай бұрын
class Solution { public int candy(int[] ratings) { int n = ratings.length; if (n == 0) return 0; int sum = 1; // Start with the first child int up = 0, down = 0, peak = 0; for (int i = 1; i < n; i++) { if (ratings[i] > ratings[i - 1]) { up++; down = 0; peak = up; sum += up + 1; // Add candies for the peak } else if (ratings[i] < ratings[i - 1]) { down++; up = 0; sum += down; // Adjust peak if down exceeds the previous up if (down > peak) { sum += 1; } } else { // Reset counters for flat sections up = down = peak = 0; sum += 1; } } return sum; } } // Up and Down Counters: Track the length of increasing (up) and decreasing (down) sequences. // Peak Adjustment: If a down sequence is longer than the preceding up sequence, the peak value is adjusted to ensure the correct number of candies is distributed. // Edge Case Handling: The code includes resets and adjustments to manage cases where ratings are flat or transition between increasing and decreasing sequences.
@VibavMahendran
@VibavMahendran 5 ай бұрын
I am encountering the same issue
@udhavMohata
@udhavMohata 5 ай бұрын
Few edge cases are not handled, related to flat case, check above solution by @rishabhkumar2062
@furqanmajeed6731
@furqanmajeed6731 4 ай бұрын
when u are moving downwards the first value that will be added in sum will be 2 in your code just change the order 1) sum+=down 2)down++;
@tanishqchauhan8053
@tanishqchauhan8053 7 ай бұрын
please run the code youself at last it shows error many times
@surendrathakur6567
@surendrathakur6567 2 ай бұрын
java solution class Solution { public int candy(int[] r) { int n = r.length; if (n == 1) return 1; // Only one child, requires 1 candy. int ans = n; // Start with 1 candy for each child. int i = 1; while (i < n) { // Skip equal ratings, as they get 1 candy each. if (r[i] == r[i - 1]) { i++; continue; } // Handle increasing sequence. int peak = 0; // Count additional candies for increasing sequence. while (i < n && r[i] > r[i - 1]) { peak++; ans += peak; i++; } // Handle decreasing sequence. int down = 0; // Count additional candies for decreasing sequence. while (i < n && r[i] < r[i - 1]) { down++; ans += down; i++; } // Adjust for the peak in the valley where increasing and decreasing meet. ans -= Math.min(peak, down); // Avoid double-counting peak. } return ans; } }
@JaydeepJayswal231
@JaydeepJayswal231 Ай бұрын
what if peak elements are multiple, then you are adding only 1 for every other peak element, not the value of peak, please answer if anybody knows
@kartikdalai7998
@kartikdalai7998 Ай бұрын
Still by adding only one it will work . As rest will no need to change,
@ashusingh0079
@ashusingh0079 Ай бұрын
how does this code will work for 1,2,3,3,3,3
@THOSHI-cn6hg
@THOSHI-cn6hg 7 ай бұрын
Great
@durgeshjadhav01
@durgeshjadhav01 7 ай бұрын
[1,0,2] the second approach fails in this test case , not able to submit it on leetcode
@mahiverma7692
@mahiverma7692 7 ай бұрын
class Solution { public int candy(int[] ratings) { int n=ratings.length; int[] left=new int[n]; left[0]=1; for(int i=1;iratings[i+1]) cur=right+1; else cur=1; right=cur; sum+=Math.max(cur, left[i]); } return sum; } } It works , hope it helps
@aryankumar3018
@aryankumar3018 5 ай бұрын
Understood
@harshalrelan3113
@harshalrelan3113 8 ай бұрын
the 2nd O(2N) doesn't seem to be working.... pls cross check
@Ajay-cv1zs
@Ajay-cv1zs 7 ай бұрын
yes the right variable is not updated correctly for else case. Actually u don't need the right variable sum:= max(1,candies[n-1]) cur:=1 //right traversal for i:=n-2;i>=0;i--{ if ratings[i]>ratings[i+1]{ cur++ }else{ cur=1 } sum+=max(candies[i],cur) candies[i] = max(candies[i],cur) }
@AKS-l3m
@AKS-l3m Ай бұрын
undersood
@pradeepkumawat1220
@pradeepkumawat1220 8 ай бұрын
First like 🎉
@mainaksen5064
@mainaksen5064 3 ай бұрын
15:46
@rishabhkumar2062
@rishabhkumar2062 6 ай бұрын
Striver i made changes to your code , to include some of the edge cases , this is my code " class Solution { public int candy(int[] arr) { int i =1; int sum =1; int n = arr.length-1; while(i
@GokulGajapathi
@GokulGajapathi 6 ай бұрын
thanks a lot bro. I got confused and got stuck for 3 days in this problem
@suryakalyan5286
@suryakalyan5286 4 ай бұрын
It's working... Guess this comment should be pinned.
@shreyxnsh.14
@shreyxnsh.14 3 ай бұрын
Optimised bruteforce solution, with just one vector: class Solution { public: int candy(vector& ratings) { vector vec(ratings.size()); vec[0] = 1; for(int i=1;i ratings[i-1]){ vec[i] = vec[i-1] + 1; }else{ vec[i] = 1; } } for(int i=ratings.size()-2;i >= 0; --i){ if(ratings[i] > ratings[i+1]){ vec[i] = max(vec[i+1] + 1, vec[i]); }else{ vec[i] = max(vec[i], 1); } } return accumulate(vec.begin(), vec.end(), 0LL); } };
@calisthenics5247
@calisthenics5247 6 ай бұрын
Can anyone suggest me how to think of intuition by myself? I can only solve medium level problems by my self(not every medium but 30%) but can't solve hard level problems
@luckygarg2294
@luckygarg2294 28 күн бұрын
Most of the optimal algorithms you can't think yourself, you have to know about them already to catch the intuition, says Striver himself
@kinjalkyadav6359
@kinjalkyadav6359 5 ай бұрын
Amazon interview question!
@Ajay-cv1zs
@Ajay-cv1zs 7 ай бұрын
O(2N) solution, actually u dont need right variable. sum:= max(1,candies[n-1]) cur:=1 //right traversal for i:=n-2;i>=0;i--{ if ratings[i]>ratings[i+1]{ cur++ }else{ cur=1 } sum+=max(candies[i],cur) candies[i] = max(candies[i],cur) }
@LIGHT2DARKNess1929
@LIGHT2DARKNess1929 7 ай бұрын
Is there anyone who completed the whole playlist?????
@shashankvashishtha4454
@shashankvashishtha4454 6 ай бұрын
understood
@storm19019
@storm19019 7 ай бұрын
?
@iamnottech8918
@iamnottech8918 6 ай бұрын
This mic is scary at night 3am
@hiteshpatwal9688
@hiteshpatwal9688 8 ай бұрын
Livestream of weekly and biweekly leetcode needed 🫡✅✅✅or else answers video of each contest please bro 😔😔
@vigneshs1852
@vigneshs1852 8 ай бұрын
He also has his life bro..he is working hard for doing this ...there are some small youtubers who are doing those contest answers😊😊😊
@saimasyeda6544
@saimasyeda6544 2 ай бұрын
Understood
@abhinanda7049
@abhinanda7049 3 күн бұрын
understood
@fanofabdevillersandmathslo5960
@fanofabdevillersandmathslo5960 16 күн бұрын
Understood
L13. Fractional Knapsack Algorithm
18:41
take U forward
Рет қаралды 68 М.
L1. Introduction to Stack and Queue | Implementation using Data Structures
1:05:06
Mom Hack for Cooking Solo with a Little One! 🍳👶
00:15
5-Minute Crafts HOUSE
Рет қаралды 23 МЛН
Sigma Kid Mistake #funny #sigma
00:17
CRAZY GREAPA
Рет қаралды 30 МЛН
When you have a very capricious child 😂😘👍
00:16
Like Asiya
Рет қаралды 18 МЛН
L11. Valid Parenthesis String | Multiple Approaches
26:09
take U forward
Рет қаралды 64 М.
Delhi Shocks India! | Sunday Show
42:16
Sarthak Goswami
Рет қаралды 51 М.
The Most Beautiful Equation in Math
3:50
Carnegie Mellon University
Рет қаралды 14 МЛН
I Spent 100 Hours Inside The Pyramids!
21:43
MrBeast
Рет қаралды 27 МЛН
Big-O Notation - For Coding Interviews
20:38
NeetCode
Рет қаралды 568 М.
Lecture 1: Algorithmic Thinking, Peak Finding
53:22
MIT OpenCourseWare
Рет қаралды 6 МЛН
5 Simple Steps for Solving Any Recursive Problem
21:03
Reducible
Рет қаралды 1,3 МЛН
Mom Hack for Cooking Solo with a Little One! 🍳👶
00:15
5-Minute Crafts HOUSE
Рет қаралды 23 МЛН