DP 18. Count Partitions With Given Difference | Dp on Subsequences

  Рет қаралды 211,981

take U forward

take U forward

Күн бұрын

Пікірлер: 656
@takeUforward
@takeUforward 2 жыл бұрын
I need your support, and you can do that by giving me a like, and commenting "understood" if I was able to explain you. Keeping a like target of 500 ❤✌🏼
@iamnoob7593
@iamnoob7593 11 ай бұрын
understood
@himalayadebbarma-we4pt
@himalayadebbarma-we4pt 5 ай бұрын
Understood
@shubhamshukla4215
@shubhamshukla4215 3 ай бұрын
what if test case in dp17 is like {2, 0 , 0 , 4 , 2 ,2} and sum = 4 , then will this solution work ? i guess at the time whenever we found sum == 0 at index > 0 , then we have to calculate number of zero till index == 0 let's suppose it is z , and then retum 2^z . What everyone think about it ?
@AbhishekKumar-cv1dh
@AbhishekKumar-cv1dh Жыл бұрын
I'll be honest, I was bamboozled with the 0's in array edge case since DP17 and I was simply unable to find a clear answer from the comments. Had I simply closed my eyes and went ahead with DP 18, I would have legit saved ~ 2 hours of confusion!! Thankyou so much Striver, this lecture cleared all my doubts 🔥🔥🔥🔥🔥
@mayanksingh7501
@mayanksingh7501 7 ай бұрын
Those confusion and doubts and 2 hours will only help in longer run. Good work on not directly jumping to another video without clearing your doubts on your own.
@after_dark_777
@after_dark_777 7 ай бұрын
for real should have moved on to this video those comments were so confusing
@SamreenAftab-lg8tx
@SamreenAftab-lg8tx 6 ай бұрын
Samee
@solitucedagar4298
@solitucedagar4298 5 ай бұрын
sameeeeeeeeeeee
@nikhilmadaan29
@nikhilmadaan29 6 ай бұрын
hats off man,, spent 2 hours on DP17 to fix that but after watching this DP 18 everything went super smooth
@Aniruddha_Chowdhury
@Aniruddha_Chowdhury 7 ай бұрын
understood until 14:00 ❤ . Will learn the optimization later
@saketsoni2587
@saketsoni2587 Жыл бұрын
I studied DP from aditya verma, but was never able to figure out how to handle the zeros in the array, you made it super easy, Thanks!
@entertainmenthub373
@entertainmenthub373 Жыл бұрын
but aditya verma always tell you the in=dentification and where u can use this apparoach nd similar questions he is the god of cp ik he skip the case of 0 in array but aditya verma is for cp where u can use which approach and how to identify which approach by seeing solution
@iamnoob7593
@iamnoob7593 11 ай бұрын
@@entertainmenthub373 God of cp is tourist.
@divyanshrawat2859
@divyanshrawat2859 6 ай бұрын
its not like he was not able to figure out , he always gives an intution to solve the problem , not like come and tells you the whole solution.
@saumyasharma9993
@saumyasharma9993 Ай бұрын
aditya vermas approach works with zeroes as well, as in that we subtract dp[i-1][j-arr[i-1]]
@PIYUSH61004
@PIYUSH61004 2 жыл бұрын
The deduction of (totalSum - D) / 2 was amazing. Understood!
@pulkitchausali1354
@pulkitchausali1354 2 жыл бұрын
Already understood before starting of video that's what Striver teaches us
@saurabhsaha6958
@saurabhsaha6958 8 ай бұрын
Striver's concept explanation is so cool, easy and easily get stuck into the head. I wish to meet him one day and say a lot of thanks to him.
@ankanbasu7381
@ankanbasu7381 2 жыл бұрын
4:48 or I think, we can go 1 step deeer into indx = -1 then base case would be simpler if (indx == -1) { if (sum == 0) return 1; else return 0; }
@introvert9112k
@introvert9112k Жыл бұрын
Then how do you take care of base case in Tabulation. As dp array cannot have -ve indexes.
@RTXCR7
@RTXCR7 Жыл бұрын
@@introvert9112k for that i think we would need to make 1 indexed arrays of size n+1 having an extra 0 index free
@cs26divyanshisachan37
@cs26divyanshisachan37 10 ай бұрын
Understood! Hats off to ur dedication, u are still teaching while suffering from fever.
@harshitsharma5647
@harshitsharma5647 2 жыл бұрын
Superb Bhaiya guys watch at 10:10 Amazing Concept Again and again Thankyou bhaiya Aka Striver
@chetanthakral5322
@chetanthakral5322 2 жыл бұрын
Another modified target could be (difference + totalSum)/2; To explain this how this came is : s1= sum of elements in subset 1 s2 = sum of elements in subset 2 s1 - s2 = d (We need to find 2 subsets with difference d ) s1 + s2 = totalSum (We know the sum of 2 subsets would be equal to the total sum of array) Adding these 2 equations , we get s1 = (d + totalSum)/2, thus we only need to find a subset with sum s1.
@takeUforward
@takeUforward 2 жыл бұрын
But this will increase the space req :)
@chetanthakral5322
@chetanthakral5322 2 жыл бұрын
@@takeUforward Oh Okay , I didn't think about that !
@varunaggarwal7126
@varunaggarwal7126 Жыл бұрын
@@chetanthakral5322 lol, I thought the same thing, but its not pure math its cs.
@UCSParnashreeDas
@UCSParnashreeDas Жыл бұрын
@@varunaggarwal7126 how this increases the space.. can u explain
@varunaggarwal7126
@varunaggarwal7126 Жыл бұрын
@@UCSParnashreeDas it's been 1 month,lol i have to revise this dp, but I guess you can see + sign while striver is subtraction, means less
@parthsalat
@parthsalat 2 жыл бұрын
Guys! For DP 17, Memoization code, striver's approach is correct (6:38), but here's a cleaner alternative for the base case: if(ind
@abhishekgururani6993
@abhishekgururani6993 2 жыл бұрын
It'll be hard to convert this base case to tabulation dp states as it's not well defined wrt the indices.
@parthsalat
@parthsalat 2 жыл бұрын
@@abhishekgururani6993 You're right. But the tabulation base cases are straightforward and simple. One can write that by applying basic logic.
@amitmahato6404
@amitmahato6404 2 жыл бұрын
Yes, I also tried this. got correct in both tabulation and memoization. Striver has complicated this solution a little bit.😅
@amitmahato6404
@amitmahato6404 2 жыл бұрын
@@abhishekgururani6993 Simple base case, if sum == 0, return 1; means fill all the 0 indices row with 1. The change is that you have to traverse j=0 to j
@blackblood181
@blackblood181 Жыл бұрын
we can also use : if(ind < 0){ if(sum==0) return 1; return 0; } apart from these conditions: if(ind == 0) { if(sum==0 || num==arr[0]) return 1; if(sum==0 && arr[0]==0) return 2; return 0; }
@anuragprasad6116
@anuragprasad6116 Жыл бұрын
this makes the code really simple to understand. perfect base case.
@theterror9080
@theterror9080 Жыл бұрын
Best Bhai @@anuragprasad6116
@manojnandhan8677
@manojnandhan8677 4 ай бұрын
but how will you handel -1 index in tabulation?
@narendramaurya4823
@narendramaurya4823 9 ай бұрын
Us, but the way you transformed the problem into previously solved problem is amazing , that's the way we have to think ... Thanks ❤
@stith_pragya
@stith_pragya 11 ай бұрын
UNDERSTOOD.........Thank You So Much for this wonderful video...............🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻
@adebisisheriff159
@adebisisheriff159 11 ай бұрын
Understood! Striver. The best Software Engineer himself
@gauravgogoi5240
@gauravgogoi5240 8 ай бұрын
After this video, they updated the problem! Real influencer
@balajisrinivasan6618
@balajisrinivasan6618 Жыл бұрын
Thank you striver ! Just a note : writing recursion from 0 to n-1 looks far easier to handle bases cases than writing recursion from n-1 to 0 on subsequence problems
@santoshpokhrel7693
@santoshpokhrel7693 Жыл бұрын
but for me it creates problem while writing the tabulation form. Esp. with all the subsequences questions.
@chase.2595
@chase.2595 Жыл бұрын
yeah man, we have to start from n-2 if we do 0 to n-1 in recursion@@santoshpokhrel7693
@ganeshktvb9234
@ganeshktvb9234 10 ай бұрын
yaa bro really it creates confusion in tabulation @@santoshpokhrel7693
@hashcodez757
@hashcodez757 4 ай бұрын
"UNDERSTOOD BHAIYA!!"
@tarunrao1505
@tarunrao1505 Жыл бұрын
Hello, The tabulation code is not passing all test cases in both videos dp-17 && dp-18. Is anyone facing the same problem. Pls HELP.
@aryarajendra1088
@aryarajendra1088 3 ай бұрын
same bhai
@architgupta3551
@architgupta3551 2 ай бұрын
@@aryarajendra1088 #include int countPartitions(int n, int d, vector &a) { // Write your code here. long long sum=0; for(int i=0 ; i
@kevalkishan3824
@kevalkishan3824 2 ай бұрын
@@aryarajendra1088 try doing mod with 10^9+1 dp[row][col] =(dp[row][col]%mod+ dp[row-1][col]%mod)%mod; int val = num[row-1]; if(col>=val){ dp[row][col] =(dp[row][col]%mod+ dp[row-1][col-val]%mod)%mod; }
@itsmepratham2712
@itsmepratham2712 Жыл бұрын
For Those who did not understand why total sum-d has to be even so imagine totalsum=15 and d=2 now count s2=(15-2)/2 it will give s2=6; ans s1-s2=d so s1=2+6=8 now here it is said that s1+s2=totalsum but s1+s2=14 which is not equal to total sum to total sum-d has to be even
@molymusic1188
@molymusic1188 6 ай бұрын
thankyou my guy🙌
@soumik5854
@soumik5854 4 ай бұрын
solved this problem on my own very proud of this
@dharmeshpoladiya9047
@dharmeshpoladiya9047 2 жыл бұрын
Understood 💯💯Great Explanation. Thank you very much for all you efforts🔥🔥
@aryanagrawal4794
@aryanagrawal4794 2 жыл бұрын
bhaiya in count subset problem which u had taken earlier , in tabulation the loop started from 0 to sum but when sum==0 it has been handled previously right? then it should start from 1 right? as in problem subset sum==k u started the sum loop from 1 to sum as for sum==0 we have handled it previously before the loop.
@takeUforward
@takeUforward 2 жыл бұрын
Yes u can, won’t be an issue :)
@aryanagrawal4794
@aryanagrawal4794 2 жыл бұрын
@@takeUforward yes i did that in the count subsets problem, but when I did that in the current problem of partition i.e. looping from 1 to sum it's giving WA, but when i changed to 0 to sum it's giving correct and. Why so?
@takeUforward
@takeUforward 2 жыл бұрын
@@aryanagrawal4794 because in partition at 0 there are other cases to handle. Here at 0, its take and notTake, hence
@aryanagrawal4794
@aryanagrawal4794 2 жыл бұрын
@@takeUforward ok bhaiya got it.
@madhurnarang2440
@madhurnarang2440 2 жыл бұрын
@@aryanagrawal4794 Hey can you explain it to me?
@vaibhavrai7042
@vaibhavrai7042 4 ай бұрын
To deal with the 0 case, we can also take the dp array to be of size [n+1][sum+1] and initialize the dp[n][0]=1 int[][] dp = new int[n+1][sum+1]; dp[n][0]=1; for(int index=n-1;index>=0;index--)
@Lyrics_dunya
@Lyrics_dunya 10 ай бұрын
For Problem 17 , I struggled a bit in Tabulation while writing the base cases for the new changes. All 3 cases covered, also notice the bases cases are written in reverse order, so that the priority is given to the last one if its true. One more thing since we are considering the case for i = 0, please start the 2nd loop of target from 0 till k(inclusive). Happy learning! dp[0][0] = 1 if arr[0]
@TyagiAviral
@TyagiAviral 6 ай бұрын
Hey, thank you. Great comment.
@MukeshKumar-cc3uh
@MukeshKumar-cc3uh 9 ай бұрын
Understood 👍. Hats off to your dedication for us. ♥
@gauravgogoi5240
@gauravgogoi5240 8 ай бұрын
15:00 the most important point to be noted if you are in an intervie
@manishisaxena5657
@manishisaxena5657 Жыл бұрын
actually we can make the base case as if(index == -1) { if(tar == 0) return 1; return 0; }
@anuragprasad6116
@anuragprasad6116 Жыл бұрын
underrated! taking this as a base case really simplifies the solution.
@ScienceSeekho
@ScienceSeekho 2 жыл бұрын
understood. Also thanks for explaining Space Optimization so good. I am from tier-3 mechanical never knew all these stuff
@yashshukla1637
@yashshukla1637 11 күн бұрын
Done. Understood the concepts so well.
@adityasaini7165
@adityasaini7165 7 күн бұрын
we can also do like this, private static int count(int i, int[] num, int k){ if(i == num.length){ if(k == 0){ return 1; }else{ return 0; } } int take = 0; if(k >= num[i]) take = count(i + 1, num, k - num[i]); int notTake = count(i + 1, num, k); return (take + notTake) % MOD; }
@akr1831
@akr1831 2 жыл бұрын
Thankyou very much for explaining base case of last question. I was stacked for last 6 hours. ❤️❤️
@anveshkarra3861
@anveshkarra3861 2 жыл бұрын
understood , the space optimization is amazing sir
@tasneemayham974
@tasneemayham974 Жыл бұрын
UNDERSTOOODD!!! Thank you, Striver!!
@SaiPhaniRam
@SaiPhaniRam Ай бұрын
Python implementation: def countPartitions(n: int, d: int, arr: List[int]) -> int: ''' Carefully analyze the problem. Let S1, S2 be the sum of two different subsets S1 + S2 = total_sum of array elements Goal: Count the subsets, such that (S1 >= S2) and (S1 - S2 = D) total_sum = S1 + S2 => S1 = total_sum - S2 From S1 - S2 = D total_sum - S2 - S2 = D S2 = (total_sum - D) // 2 (or) S1 = (total_sum + D) // 2 Problem boils down to finding number of subsets whose sum is (total_sum - D) // 2 (or) sum is (total_sum + D) // 2 ''' ''' Space Optimization ''' if not arr: return 0 total_sum = sum(arr) target = (total_sum - d) // 2 # print('Target: ', target) if (total_sum < d) or (total_sum - d) % 2 != 0: return 0 mod = 10 ** 9 + 7 prev = [0 for t in range(target + 1)] # Base Cases # 1. At index 0, if val == 0 => 2 (pick/ unpick doesn't matter) # 2. Else, At index 0, val 1 way (pick it) prev[0] = 2 if arr[0] == 0 else 1 if arr[0] != 0 and arr[0]
@GManiKarthik
@GManiKarthik 19 күн бұрын
#Understood #DP18 #Hatsoff #Striver
@champu5645
@champu5645 2 жыл бұрын
I thing the simplest way to get rid of so many conditions of 0's we can simply start the recursion for 0 to n-1; then we will get correct ans i.e.4;
@nithish_raina
@nithish_raina 2 жыл бұрын
Yes, and it would also work even if the array doesn't contains any zeroes.. The base cases are also so simple to handle over here.
@VinayKumar-xs6el
@VinayKumar-xs6el 3 ай бұрын
can u share the code here please that starts from 0 & ends at n-1
@champu5645
@champu5645 3 ай бұрын
@@VinayKumar-xs6el will share soon, i also have to check where i have written the code. It's been 2 years
@AmanBawane-o9q
@AmanBawane-o9q 5 ай бұрын
another base case(Better and Concised): if(ind
@techietech7073
@techietech7073 2 жыл бұрын
for DP 17 for [ 7,1,0,2,5] with tar=7 Method 1: originalAns*(pow(2,n)) Method2: Changes in base case will that work? I can see from recursion tree there would be redundant calls at level where 0 is considered
@YatriSpecial
@YatriSpecial 2 жыл бұрын
How do I write the base case in tabulation, Could you please tell me?
@nithish_raina
@nithish_raina 2 жыл бұрын
Method 1 is time intensive if let's say the no of zeroes were 15-20 in an array...Hence method 2 with handling zero in the base cases is required at such cases.
@ritikshandilya7075
@ritikshandilya7075 6 ай бұрын
Great Explanation Striver , Thanks
@andrewcenteno3462
@andrewcenteno3462 6 ай бұрын
That algebra at 10:15 is crazy I would never see that under the time constraints of a real interview. It's brilliant tho
@chaitralishinde7815
@chaitralishinde7815 4 ай бұрын
Understood better than ever!
@rohandevaki4349
@rohandevaki4349 2 жыл бұрын
at 15:53 , the target should run from 1 to sum right? we have run from 1 to sum in the count subsequences with sum k also, why did you take from 0 to sum?
@TheDebuggers-fx9vp
@TheDebuggers-fx9vp 3 ай бұрын
i thnk a sligh change in base case can handle all the case well,instead of returning when we encounter the target to 0; if we keep exploring until the end of the tree then we can get our desired result class Solution { public: int helper(int arr[], int n, int sum, vector& dp) { // Base case: If there are no elements left if (n == 0) { return (sum == 0) ? 1 : 0; } // If the subproblem has already been solved, return the stored result if (dp[n][sum] != -1) return dp[n][sum]; // Compute the result for this subproblem int notPick = helper(arr, n - 1, sum, dp); int pick = 0; if (arr[n - 1]
@ShahNawaz-cx3pi
@ShahNawaz-cx3pi 5 ай бұрын
*********** Iterative Code for the count number subsequence whose sum is k ( & 0
@nehakaushik3602
@nehakaushik3602 2 жыл бұрын
OMG bhaiya ...simple "genius"
@shoryapawar2219
@shoryapawar2219 Жыл бұрын
Understood Thanks Striver for this Dp series
@parthsalat
@parthsalat 2 жыл бұрын
DP 18 starts from 7:25
@Sneha-gb7iq
@Sneha-gb7iq 2 ай бұрын
For tabulation, we can do dp[0][0]=1 and dp[0][nums[0]]+=1 Without checking for all cases
@sonicboom6635
@sonicboom6635 Жыл бұрын
In the space optimized solution why the loop sum=1 to target doesn't work as we have been doing previously and setting curr[0] =1 since for any index with target as 0 there is only single subset. Can someone explain please?
@Parthj426
@Parthj426 5 ай бұрын
us But i got confused as in DP 18 ques , it is written that two partitions have their union as Whole array . It should have been given that both are exclusive of each other , for being self-explanatory well.
@sahilarya9510
@sahilarya9510 2 жыл бұрын
please tell us the time when this amazing course will get end......expected time??
@dharsan.s7937
@dharsan.s7937 2 жыл бұрын
March
@kathanvakharia
@kathanvakharia Жыл бұрын
Understood...Completed 18/56
@ntgrn-pr5yx
@ntgrn-pr5yx Ай бұрын
understood , thank you striver
@ranasauravsingh
@ranasauravsingh 2 жыл бұрын
UNDERSTOOD... ! Thanks striver for the video... :)
@musichub2168
@musichub2168 2 жыл бұрын
Understood 💯💯Great Explanation
@arpitrajput6424
@arpitrajput6424 2 жыл бұрын
In Lecture 17 , we can sort the vector and reverse it, then no need to change base case it will work absolutely fine.
@riddhibandyopadhyay584
@riddhibandyopadhyay584 2 жыл бұрын
Yes, but it will take extra time complexity
@arpitrajput6424
@arpitrajput6424 2 жыл бұрын
@@riddhibandyopadhyay584 ya you're right but can be done ✅ with this approach .👍
@priyankabagal9269
@priyankabagal9269 2 жыл бұрын
You have literally made dp look so easy !
@tallalhabib4526
@tallalhabib4526 Жыл бұрын
What if we find with target = totalsum Then at n-1 iteration of tabulation find S1 and S2 by totalsum - S1. Then If S1>=S2 and S1-S2=D we can return True else False
@beginnertopro7265
@beginnertopro7265 2 жыл бұрын
tabulation -; previous question include 0 in question;- void Vikash() { int n, k; cin >> n >> k; vector ans(n); F(i, 0, n) cin >> ans[i]; vector dp(n, vector(k + 1, 0)); // cout
@undefined_exception_0
@undefined_exception_0 2 жыл бұрын
There is no need of the first loop. int countSubsets(int arr[] , int size , int k) { vector dp (size , vector (k+1 , 0)); // base case if(arr[0] == 0){ dp[0][0] = 2; }else{ dp[0][0] = 1; } if(arr[0] != 0 && arr[0]
@ayushidalal5488
@ayushidalal5488 Жыл бұрын
@@undefined_exception_0 This works perfectly. Thank you!
@VikasGupta-ok9lh
@VikasGupta-ok9lh 2 жыл бұрын
In that case my recursive code was going from 0 to n-1 and to avoid case of zero I sorted my array hence all the zero cases were sorted
@inderjotsingh5868
@inderjotsingh5868 Жыл бұрын
you don' t even need this , just go from 0 -> n , and if at n , target == 0, return 1 else 0 , all other cases are already been taken care off , if you do in this way . How ? our code will do this will we are making the recursive calls at n-1
@shriRadheHariom
@shriRadheHariom 5 ай бұрын
Understood, well explained.
@shubh625
@shubh625 4 ай бұрын
ok
@uvs_6032
@uvs_6032 Жыл бұрын
I have a doubt. The question says the the union of two subsets will give the original array , that means there can be repeating elements and its not necessary that S1 + S2 = totalSum E.g -> arr = {1, 2, 3, 4, 5} totalSum = 15 S1 = {1, 2 ,3, 4} S2 = {1, 5} sum1 = 1 + 2 + 3 + 4 = 10 sum2 = 1 + 5 = 6 The union of the above two will give original array but sum1 + sum2 != totalSum. So how is the code working ? Is the problem statement wrong?
@kushbudhiraja4927
@kushbudhiraja4927 Жыл бұрын
you are right code is only passing 6 test cases not all
@paracetamol9116
@paracetamol9116 6 ай бұрын
the question's wording is wrong, look at the same question on gfg, won't see "union" written anywhere.
@ankishkhandelwal1061
@ankishkhandelwal1061 2 жыл бұрын
In case arr =1,2,3,4 Diff =2 S1>S2 Target is =(10-2)/2 =4 Give 2 as answer 4 3,1 But 1+2+3-4=diff How this case will handle
@ShahNawaz-cx3pi
@ShahNawaz-cx3pi 2 жыл бұрын
In question it is mentioned that the union of both the set is equal to the given array.
@ankishkhandelwal1061
@ankishkhandelwal1061 2 жыл бұрын
@@ShahNawaz-cx3pi got it
@TanviPoddar-f1k
@TanviPoddar-f1k 7 ай бұрын
At 15:15, shouldn't the condition be ((nums[0] != 0)&&(nums[0] == target)) ??
@TON-108
@TON-108 Жыл бұрын
Understood Bhaiya!
@akashkumarsingh3595
@akashkumarsingh3595 2 жыл бұрын
If we have handled the case num[0] == 0 previously then why we are checking it again for num[0]
@swagcoder
@swagcoder Жыл бұрын
Can anyone please explain why target is starting from 0 here? in all other problems it's starting from 1. If I take 1, some test cases are failing
@affanrahman5711
@affanrahman5711 2 жыл бұрын
In lecture 17, can we handle the cases having zeroes by just multiplying our previous answer with pow(2,n) where n is the no. of zeroes
@takeUforward
@takeUforward 2 жыл бұрын
I discussed that only, but that adds a log n
@sourabhchoudhary7289
@sourabhchoudhary7289 2 жыл бұрын
@@takeUforward Does 1ll
@sanskarjaiswal4394
@sanskarjaiswal4394 Жыл бұрын
Instead of changing the code we can just add a if statement before "take" variable that if arr[index]== 0 then skip it...
@tami9154
@tami9154 Жыл бұрын
wouldn't it be better to go an ind
@sakshamsengar9798
@sakshamsengar9798 2 жыл бұрын
if we keep base condition like this then we dont have to check for individual case ....this is giving right answer..... if(i==n){ if(s1==0)return 1; return 0; } if(s1
@prabhakaran5542
@prabhakaran5542 9 ай бұрын
Understood ❤
@abhisheks7450
@abhisheks7450 4 ай бұрын
why doesnt the for(int i = 0;i
@kushjoshi9716
@kushjoshi9716 2 жыл бұрын
Nicely Explained! Understood!
@anshugangwar7344
@anshugangwar7344 2 жыл бұрын
Calculating Max Sum of Array with the following condition, If A[i] element contributing in max sum,than you can't consider A[i]-1 and A[i]+1 element for max sum contribution, if present in array . Note: Elements of the array can be repeated multiple times. It's unsorted. It can have 1 to n number of element. eg: int A[ ]={1,6,7,1,2,3,3,4,5,5,5,6,9,10}; If I consider 10 as contributing max sum, I can consider 9 and 11. (Here 11 is not present but 9 is present still we can’t consider it). If I consider 5 (total max sum contribution 5*3) but can’t consider 4 and 6. I have tried sorting and storing index and count in the ordered map. Also try to compare with unbounded knapsack criteria. Still, I was struggling with an optimal and clear idea to calculate. Any idea how to approach it .
@AnanditaTiwari-c7m
@AnanditaTiwari-c7m Жыл бұрын
Create an array dp of size n, where n is the length of the input array A. Initialize all elements of dp to 0. Sort the input array A in ascending order to simplify the comparison process. Iterate through each element A[i] in the sorted array A. For each element A[i], update the maximum sum at index i in the dp array based on the following condition: If A[i] is the first occurrence in the sorted array or A[i-1] and A[i+1] are not present in the sorted array, then set dp[i] to dp[i-1] + A[i]. Otherwise, set dp[i] to the maximum value between dp[i-1] (excluding A[i]) and dp[i-2] + A[i] (including A[i]). After iterating through all elements in the sorted array, the maximum sum will be the maximum value in the dp array.
@shreyashtech8556
@shreyashtech8556 9 ай бұрын
bro doing gods work
@harisrashid0773
@harisrashid0773 2 жыл бұрын
int gfg the case where 0 can be in the begining can be solved by sorting given array in decreasing order but this will increase time compl,but will still pass test cases;
@the_shridhar
@the_shridhar 7 ай бұрын
just add this in previous question: ``` if (i < 0) { return !target; } ```
@SatyamKumar-bw4vi
@SatyamKumar-bw4vi Жыл бұрын
Hare Krishna..!! understood.
@mrinmoyhalder7293
@mrinmoyhalder7293 2 жыл бұрын
hey can anyone please clear my doubt. I'm applying DP-16 concept.like after filling the tabulation with boolean, check and try for every s1, that it's possible to get standing on last index, if possible then calculate s2 and check the condition given in the qsn and increment count, Now this method is not working, I think it's because the tabulation is not recording duolicacy, e.g, In array if the sum 7 is made by more than one way, then it's not taking that record, and while checking for (s1>s2 && s1-s2==d), only once the count is increasing, is it the actual reason of failing ?
@atulkumarsingh6507
@atulkumarsingh6507 2 жыл бұрын
TARGET1: MATRIX- COMPLETED, TARGET2-ARRAY/STRING: COMPLETED, eagerly waiting for TARGET3:?
@shiershdwivedi742
@shiershdwivedi742 2 жыл бұрын
"Hi Striver, This is Thriver here hope you are doing extremely well "😅
@shauryatomer1058
@shauryatomer1058 2 ай бұрын
thanks for another great video
@namanchandak1532
@namanchandak1532 2 жыл бұрын
at 14:03 why you removed for() dp[i][0]=1;
@madmaxgaming5864
@madmaxgaming5864 Жыл бұрын
just mind blowing how you came up with the modified target, kyse kar lete ho bhaiya?
@stain0p101
@stain0p101 Жыл бұрын
Thank you striver, made it super easy and interesting to learn DP. "UNDERSTOOD" 💓💓
@ramyasree4986
@ramyasree4986 2 жыл бұрын
completed subsequences set problems great learning
@riturajseal6945
@riturajseal6945 2 жыл бұрын
Is the condition num[0]
@neerajgarg9096
@neerajgarg9096 2 жыл бұрын
The condition is necessary because we are declaring dp vector of size n×(tar+1) so lets if our arr[0]th element is greater then tar (arr[0]>tar) then if we do dp[0][num[0]] it will give us TLE as we fixed its size to (tar+1) but we are storing value at a index which does not exist so thats why that condition is important. Hope u understand ;)
@mmbmmbmmb
@mmbmmbmmb Жыл бұрын
@@neerajgarg9096 THANK YOU SO MUCH! my brain was hurting thinking why but now i see
@sujalgupta6100
@sujalgupta6100 2 жыл бұрын
Understood. Best on whole yt.
@mayankmalhotra21
@mayankmalhotra21 Жыл бұрын
if someone is going from 0 to n if(i==arr.length) { if(tar==0) return 1; else return 0; } this will handle the case for zero (1, 0,0 ) will give -> 4 (if tar = 1)
@hrushikesh-1914
@hrushikesh-1914 Жыл бұрын
Understood. Thankyou sir.
@RaghavSharma-nt3hr
@RaghavSharma-nt3hr 2 жыл бұрын
CHECK:- 9:30 - 12:14
@Jainam-17-18
@Jainam-17-18 Жыл бұрын
space optimization code for previous question(DP-17): class Solution{ public: int perfectSum(int arr[], int n, int sum) { vector prev(sum+1,0); if(arr[0] == 0){ prev[0] = 2; }else{ prev[0] = 1; } if(arr[0] != 0 && arr[0]
@arinmodi8884
@arinmodi8884 2 жыл бұрын
Hey, Striver I understood the logic in this but how are you able to think of using logic like this very quickly ? , i didn't get that by looking at the question.
@rajatsingh4286
@rajatsingh4286 Жыл бұрын
Striver can you explain the approach when there are negative elements also in the array
@sarthakkrishna3492
@sarthakkrishna3492 Жыл бұрын
use a map
@rajatsingh4286
@rajatsingh4286 Жыл бұрын
@@sarthakkrishna3492 how ? can you explain with example
@shubhrajyotipoddar1684
@shubhrajyotipoddar1684 7 ай бұрын
if(k==0) dp[ind][k]= 1; if(ind==0) return (arr[ind]== k)?1:0; I feel like not returning and instead adding 1 to the dp should do the trick And in case of tabulation: dp[0][0] = 1; this should do instead of the for loop of ind= 0 to n-1{dp[i][0] =1}
@DevashishJose
@DevashishJose Жыл бұрын
understood. Thank you so much
DP 20. Minimum Coins | DP on Subsequences | Infinite Supplies Pattern
34:15
Сестра обхитрила!
00:17
Victoria Portfolio
Рет қаралды 588 М.
Quilt Challenge, No Skills, Just Luck#Funnyfamily #Partygames #Funny
00:32
Family Games Media
Рет қаралды 55 МЛН
My scorpion was taken away from me 😢
00:55
TyphoonFast 5
Рет қаралды 1,7 МЛН
Chain Game Strong ⛓️
00:21
Anwar Jibawi
Рет қаралды 40 МЛН
I Solved 100 LeetCode Problems
13:11
Green Code
Рет қаралды 274 М.
DP 17. Counts Subsets with Sum K | Dp on Subsequences
36:57
take U forward
Рет қаралды 232 М.
Gitlab DELETING Production Databases | Prime Reacts
17:27
ThePrimeTime
Рет қаралды 357 М.
You have 30 seconds. Viral riddle from The 1% Club
8:42
MindYourDecisions
Рет қаралды 19 М.
The Ultimate Tier Programming Tier List | Prime Reacts
26:57
ThePrimeTime
Рет қаралды 502 М.
How I Failed the Google Coding Interview (and lessons I learned)
14:24
DP 22. Coin Change 2 | Infinite Supply Problems  | DP on Subsequences
22:17
11 Count the number of subset with a given difference
16:51
Aditya Verma
Рет қаралды 261 М.
Making an Algorithm Faster
30:08
NeetCodeIO
Рет қаралды 172 М.
Сестра обхитрила!
00:17
Victoria Portfolio
Рет қаралды 588 М.