Dp 16. Partition A Set Into Two Subsets With Minimum Absolute Sum Difference | DP on Subsequences

  Рет қаралды 288,355

take U forward

take U forward

Күн бұрын

Пікірлер: 1 100
@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 ❤✌🏼
@divyaporwal589
@divyaporwal589 2 жыл бұрын
It is not working with negative numbers, for example the array is -36,36 and then the target is zero
@harshitrawat138
@harshitrawat138 2 жыл бұрын
@@divyaporwal589 Dp requires array and array can't have negative indexes. If array contains negative numbers you can subtract the most negative number of given array (minx) from every element array so the all the elements will be positive.
@spytonic4171
@spytonic4171 2 жыл бұрын
@@harshitrawat138 truee but the problems comes when there is a random so if we check for negetive numbers at starting and find diff with each number the we can return it other wise we can continue this algo nice idea
@kaushalwaghela429
@kaushalwaghela429 2 жыл бұрын
understood if possible, please give leetcode and gfg problem links also. thanks :)
@trendtoyou7967
@trendtoyou7967 2 жыл бұрын
We need not calculate minimum repeatedly. Traverse last row in dp array in reverse order and return first true cell.... Total-2*i
@aryashjain7893
@aryashjain7893 2 жыл бұрын
understood, but the leetcode question mentioned in the sheet requires meet in the middle approach as it has got negative values, and tabulation fails in this case.
@ankitanand1539
@ankitanand1539 Жыл бұрын
Use long long
@fettuccine794
@fettuccine794 10 ай бұрын
Exactly !!!
@dhananjaygorain6375
@dhananjaygorain6375 9 ай бұрын
@@ankitanand1539 still it showing runtime error can you give your code please
@gamersgame43
@gamersgame43 8 ай бұрын
use unordered_set?
@ganishk3568
@ganishk3568 4 ай бұрын
@aryadhjain7893 that is not an issue if you have initial offset of 10⁷. But the problem is requires both the partitions should be of equal size.
@rishabhsinha7250
@rishabhsinha7250 3 ай бұрын
This is the first time when I am able to understand what a DP table looks like in real and how it works. Its a level up for me. ThankU Striver.
@vikasbagri1225
@vikasbagri1225 2 жыл бұрын
Understood it very well Thanks for this amazing series You really are contributing a lot to this community Best DP series in the whole youtube
@visheshagrawal8676
@visheshagrawal8676 Жыл бұрын
it took me 50 mins to solve the question without looking the answer it's all because of you the way you teach.. ✨✨✨✨
@mrsunny8299
@mrsunny8299 Жыл бұрын
understood, i dont know why i was skipping dp, it is easy, (you made it easy to understand this). Thankyou.
@pratikdas1780
@pratikdas1780 Жыл бұрын
I could do the memoized version on my own, but could never do it the bottom-up way. today, i can say that it's clear. and it was damn simple. just checking the sums my array of size n can produce. amazing insight.
@vikasgupta6701
@vikasgupta6701 2 жыл бұрын
Able to solve this problem without seeing the video and using concepts learned in past two videos. That's the power of striver's lectures. Thanks!!
@tonyconor681
@tonyconor681 Жыл бұрын
exactly
@pritimurmu7898
@pritimurmu7898 Жыл бұрын
bro how did you solve for negetives
@prashantpal3510
@prashantpal3510 11 ай бұрын
me too
@VedeshPadal-ev9tt
@VedeshPadal-ev9tt 3 ай бұрын
@@pritimurmu7898 were you able to solve this question on leetcode
@SahanaaEvan-mo6zv
@SahanaaEvan-mo6zv Жыл бұрын
Understood! Striver you are just brilliant. Your explanation and these concepts are blowing my mind off! Damn I got lucky coz i found a teacher like you! Thank you so much!
@rohitbadhai8219
@rohitbadhai8219 Жыл бұрын
We can optimize space complexity here since maximum value a subset can take for minimum absolute difference is total_sum/2 so we can make 2d vector for total_sum/2 instead of total_sum and then iterate last row of vector from last col and the first cell with true will be subset1.
@sakshisakshi5677
@sakshisakshi5677 2 жыл бұрын
You made the concept clear easily and smoothly🙌
@shreyashtech8556
@shreyashtech8556 7 ай бұрын
Dude, really thankful to you man. I solved this question and 95% of the previous questions on my own. the reason is you. your explanation is out of the world. thanx again. hope we meet in person in the near future.
@sanginigupta1312
@sanginigupta1312 2 жыл бұрын
Was able to solve this in a single go, thank you striver bhaiya, only because of these videos I'm able to develop an intuition in DP problems
@stith_pragya
@stith_pragya 10 ай бұрын
UNDERSTOOD............Thank You So Much for this wonderful video........🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻
@iamnoob7593
@iamnoob7593 10 ай бұрын
man i just dont understand how is he able to do video recording at freakin 4 AM in the morning , Very few match that level of hardwork.
@VY-zt3ph
@VY-zt3ph 2 жыл бұрын
This is the question which I was eagerly waiting for you to upload since the day you uploaded first DP lecture in this playlist.
@anshul5533
@anshul5533 2 жыл бұрын
Striver bhaiya i think it can be further optimized in terms of time and space if we take our sum as sum/2 initially (as we have taken in DP-15), then the TC : N * (k/2) and SC : (k/2) because we are just bothered about S1 till k/2
@takeUforward
@takeUforward 2 жыл бұрын
True.. concept clear hone se u urself can do these small things :P
@sparks8754
@sparks8754 2 жыл бұрын
Inspiring
@deepaksarvepalli2344
@deepaksarvepalli2344 2 жыл бұрын
I am searching for this comment... satisfied...😂
@vanshsehgal9475
@vanshsehgal9475 2 жыл бұрын
Can you explain a lit bit more? I did not clearly get what are you trying to say..
@abhishekcs5468
@abhishekcs5468 2 жыл бұрын
@@vanshsehgal9475 You basically try to find target as upperbound of sum/2 and optimize for closest. Here is the memoized solution without space optimization. --------------------------------------------------------------------------------------------------------------------------- int dfs(int ind, int upperBound, vector& nums, vector& dp){ if(ind > nums.size() - 1) return 0; if(dp[ind][upperBound] != -1) return dp[ind][upperBound]; int notTaken = dfs(ind + 1, upperBound, nums, dp); int taken = -1e8; if(nums[ind]
@nikhilprasad644
@nikhilprasad644 2 жыл бұрын
bro this problem work only for +ve numbers and not on negative numbers. pls do make a follow up for negative numbers as well, as it might come up in an interview. good companies do ask such. thanks
@SuryanshKumarPathak-m8o
@SuryanshKumarPathak-m8o Жыл бұрын
Did you come across a solution for the negative numbers?
@EerieEntertainment-mc4ce
@EerieEntertainment-mc4ce 10 ай бұрын
@@SuryanshKumarPathak-m8o agar array ka minimum element negative hai to saare element me use add krke array ko non negative banalo
@manikiran949
@manikiran949 9 ай бұрын
Hey did you find a dp solution for negative numbers ? , I have seen in leetcode that it is unsolvable with dp for negative numbers .Thanks
@ramakrishnan4356
@ramakrishnan4356 9 ай бұрын
Instead of storing in array store the same in map create map where you can store corresponding sum for values this way we can handle negatives also
@safiwasif2905
@safiwasif2905 5 ай бұрын
@@ramakrishnan4356 thx mate
@mohan_codes
@mohan_codes 4 ай бұрын
Amazing! thankyou DSA parasurama striver best teacher ever in my life.
@pritikasharma9857
@pritikasharma9857 2 жыл бұрын
Amazingly explained!. But I had a doubt won't this method fail if we have negative elements in the given array ? Could you explain this too
@amritanand1714
@amritanand1714 Жыл бұрын
Yeah it's a problem. I think we cannot solve then through this way. There are questions on leetcode with negative values. Anyone please reply if they have any solution for this?
@channelname4394
@channelname4394 2 жыл бұрын
Best explanation. understood , hope this channel reaches more people
@AquaRegia-i3u
@AquaRegia-i3u Жыл бұрын
Quick Tip 💡: If you want to solve this using memoization, you need to make sure that you call the recursive function for all possible targets. For example let the sum = 10, so target = 5. Now if you call function for 5 i.e. F(n,5) it may not always fill the complete dp grid. So you have to call all F(n,5) F(n,4) .... F(n,0) to make sure all dp[i][j] are filled. This won't affect the time complexity as if it was previously calculated it won't be calculated again due to memoization. In tabulation we go from 0 -> n, filling all dp[i][j] no matter what, so in that case it all indexes are filled.
@kishorkumarbehera5412
@kishorkumarbehera5412 Жыл бұрын
Can you give me the code for reference ?
@AquaRegia-i3u
@AquaRegia-i3u Жыл бұрын
public class Solution { public static int minSubsetSumDifference(int[] arr, int n) { int sum = 0; for(int num : arr) sum += num; int k = sum/2; if(n==1) return arr[0]; if(k==0) return 0; Boolean[][] dp = new Boolean[n][k+1]; for(int i=k; i>=0; i--) find(arr, i, n-1, dp); for(int i=k; i>=0; i--){ if(dp[n-1][i]!=null && dp[n-1][i]) return sum - (2*i); } return -1; } private static boolean find(int[] arr, int k, int i, Boolean[][] dp){ if(k==0) return true; if(i
@AquaRegia-i3u
@AquaRegia-i3u Жыл бұрын
@@kishorkumarbehera5412 added the code
@kishorkumarbehera5412
@kishorkumarbehera5412 Жыл бұрын
@@AquaRegia-i3u Instead of calling for each target we can call it for sum/2. So when we are picking and not picking we have the sum of the subset, so we can store the difference between the subset sum and the target which is total sum/2, and taking minimum of all subsets. So when returning the final answer we should check if the total sum is even or odd. Accordingly the answer would be 2*ans or 2*ans+1.
@RohitKumar-jd7un
@RohitKumar-jd7un Жыл бұрын
code for this approach bool helper(int ind,int k,vector &arr,vector &dp) { if(k==0) { return true; } if(ind==0) { if(arr[ind]==k) { return true; } else return false; } if(dp[ind][k]!=-1) { return dp[ind][k]; } bool nottake=helper(ind-1,k,arr,dp); bool take=false; if(arr[ind]
@MohammedAmrath
@MohammedAmrath Жыл бұрын
Bhayya can you explain how can we handle the negetive cases where -10^7
@dennyage4791
@dennyage4791 2 жыл бұрын
What if we have negative integers in an array, then this approach won't work ??
@jaycodes6599
@jaycodes6599 Жыл бұрын
In tabulation there is no need of this condition : arr[0] = 0 Therefore a[0] will be always less than or equal to k
@paridhijain7062
@paridhijain7062 2 жыл бұрын
Understood. Sir, You are really making great efforts for students like us. Thank you for teaching us.
@codelikebeast3971
@codelikebeast3971 Жыл бұрын
Awesome Striver , I was confused in how dp vector is formed step by step and what does it signifies, you cleared it with so much clearity . Respect
@iamnoob7593
@iamnoob7593 10 ай бұрын
same i had doubt too abt it now its clear.
@shivamdwivedi8120
@shivamdwivedi8120 2 жыл бұрын
In case of negative integers, what should we can do ?
@VishalGupta-jh9nz
@VishalGupta-jh9nz Жыл бұрын
Just add absolute value of minimum integer to every element
@avicr4727
@avicr4727 Жыл бұрын
@@VishalGupta-jh9nz can you provide me the code it will be very helpful
@VishalGupta-jh9nz
@VishalGupta-jh9nz Жыл бұрын
@@avicr4727 Yes, I can provide but it gives TLE class Solution { public: int f(int ind, int target, int sum, int size,vector& nums, int n,vector&dp ){ if(ind==-1 && size==n/2){ return abs(target-2*sum); } if(ind==-1 || size>n/2){ return 1e8; } if(dp[sum][size]!=-1)return dp[sum][size]; int notTake = f(ind-1,target,sum,size,nums,n,dp); int take = f(ind-1,target,sum+nums[ind],size+1,nums,n,dp); return dp[sum][size] = min(take,notTake); } int minimumDifference(vector& nums) { int n = nums.size(); int mini = 0; for(int i=0;i
@yogeshlamba5485
@yogeshlamba5485 Жыл бұрын
@@VishalGupta-jh9nz Consider an array , arr = [-1e7, 4, 7, 1e8, 6] The minimum number here is -1e7, and if go for adding this to all elements, adding it to 1e8 will be out of INT_MAX.
@keshavbaheti7327
@keshavbaheti7327 Жыл бұрын
​@@yogeshlamba5485 use long long and guess what 1e7 +1e8 is not equal to 1e9.😊
@cyro_-ej6xm
@cyro_-ej6xm 5 ай бұрын
kudos striver, you are the reason i got my confidence back , thanku so much , appreciate all the hard work you do , it changes life of thousands .
@udaypratapsingh8923
@udaypratapsingh8923 2 жыл бұрын
you made the concept clear easily and smoothly🙌 : )
@kushalgupta2041
@kushalgupta2041 3 ай бұрын
An another apporach can be:- We just have to fix the target to the (totalSum/2) and return the minimum difference between the nearest value to the target for example the target we need is 5 and if there exist a sum of 5 then we return 0 means the target is possible and if there exist the closes value nearest to the 5 is 3 then we return 2. Here's my code hope you understand what i did:- int f(int idx, int target, vector &dp, vector &nums){ if(target == 0) return target; if(idx < 0) return target; if(dp[idx][target] != -1) return dp[idx][target]; int notPick = f(idx - 1, target, dp, nums); int pick = 1e9; if(target >= nums[idx]){ pick = f(idx - 1, target - nums[idx], dp, nums); } return dp[idx][target] = min(pick, notPick); } int minSubsetSumDifference(vector& arr, int n) { int sum = 0; for(int i = 0; i < n; i++) sum += arr[i]; vector dp(n, vector(sum / 2 + 1, -1)); int minLeftSum = sum/2 - f(n-1, sum/2, dp, arr); int minRightSum = sum - minLeftSum; return abs(minLeftSum - minRightSum); }
@prajjwalpandey2278
@prajjwalpandey2278 2 жыл бұрын
This can be alternatively solved, if we can find a subsequence with sum closest to totalSum/2. Correct me if I'm wrong.
@vedanshbhardwaj6548
@vedanshbhardwaj6548 2 жыл бұрын
ya even I did so, but somehow the space optimised solution went wrong
@amitmahato6404
@amitmahato6404 2 жыл бұрын
[2,3,7], sum/2=6, closest sum can be 5 or 7
@vedanshbhardwaj6548
@vedanshbhardwaj6548 2 жыл бұрын
@@amitmahato6404 ya but the catch is we will only check till totalSum/2....because if one is say 5, other is bound to be 7 so why check for anything greater than the totalSum/2
@amitmahato6404
@amitmahato6404 2 жыл бұрын
@@vedanshbhardwaj6548 yeh, S1=5, SO S2 WILL BE 7, MIN DIFF IS 2
@JeevanGaikwad-G1
@JeevanGaikwad-G1 2 жыл бұрын
Understood. Very nicely explained the tough problem in an elegant way. Thanks.
@aryanbhagat6252
@aryanbhagat6252 2 жыл бұрын
How do we do this with negative elements as well?
@kotipallimadhumeher71
@kotipallimadhumeher71 2 жыл бұрын
Understood bhaiya!! In short we can say that the dp table last row defines whether the target value is possible from given array or not.Then all possible target values are derived from the dp table and we can take min diff among the all abs diff.
@amritanshusinha9401
@amritanshusinha9401 Жыл бұрын
Hey bro! Great video and explanation! Just had a small question. How would you approach a similar problem where the sizes of both the partitioned subsets must be equal?
@rishabhgupta9846
@rishabhgupta9846 Жыл бұрын
understood,able to solve by my own .What I was doing is calling memoization for every subset sum s1 which is giving me TLE. But using tabulation we don't need to call memoization again and again and can solve in one go
@bapanmandal9019
@bapanmandal9019 Жыл бұрын
In case of negative integers, what should we can do ,vaiya ?
@HarshKumar-ip5nr
@HarshKumar-ip5nr Жыл бұрын
substract min(nums.begin(), nums.end()) from each element.
@MukeshKumar-cc3uh
@MukeshKumar-cc3uh 8 ай бұрын
Understood ❤ and thanks for the inspiration by working at 4AM in the morning.
@guptashashwat
@guptashashwat 2 жыл бұрын
If array elements are negative what should we do?
@denishfuletra7863
@denishfuletra7863 Жыл бұрын
let me know if you find ans for negative elements.
@himanshujindal1532
@himanshujindal1532 2 жыл бұрын
I appreciate the hardwork you putting
@alessandrocamilleri1239
@alessandrocamilleri1239 Жыл бұрын
Great video. I simplified the minimum subset difference as follows: int i = totSum / 2; while (!dp[i]) i- -; // will not go out of bounds since i always stops at dp[0] which is always true return (totSum - i) - i;
@ishaanchandak4774
@ishaanchandak4774 Жыл бұрын
i found this one a bit harder than the previous ones but gave time watching video and doing it by myself and understood it . great work man . n
@shantanu240895
@shantanu240895 2 жыл бұрын
How would you handle this problem in case the numbers in an array are negative or zero too? The tabulation wouldn't work in such a scenario.
@sherlockholmes1605
@sherlockholmes1605 2 жыл бұрын
It would right? if we add an extra check to see if the index is going out of bounds for dp[i-1]th row.
@ihsannuruliman3656
@ihsannuruliman3656 2 жыл бұрын
it would work yeah just check of out of bounds.
@SR-we1vl
@SR-we1vl 2 жыл бұрын
Can you please share the code!
@tusharnain6652
@tusharnain6652 2 жыл бұрын
It wont work with negatives, there's a negative number case in leetcode, this solution fails there.
@jigardoshi2852
@jigardoshi2852 2 жыл бұрын
Yes agreed, this DP solution will not work when numbers are negative or 0 or for matter if totalSum of all nums is 0.
@deepanshurohilla2114
@deepanshurohilla2114 Жыл бұрын
Can we do it using Memoization techniqe of parent problem "Subset with given Sum"?? The answer is no because recursive technique always fills the cells in the table which are neccessary for solving the bigger problem, it will not always fill the whole matrix but here we need the whole (n-1)th row to be filled to do partitioning hence we can do it using tabulation only. Below is the code using pick and notPick technique very easy to understand : #define vi vector class Solution{ public: // Subset with given sum bool subsetToSumK( int n , int k, int arr[], vector &dp ){ for( int i=0; i
@krishan_aggarwal9376
@krishan_aggarwal9376 2 жыл бұрын
Please make a video regarding neagtive values too 😓. This one understood❤❤
@harshvardhangupta5323
@harshvardhangupta5323 2 жыл бұрын
wont it be the same logic?
@sumerrawat6947
@sumerrawat6947 2 жыл бұрын
@@harshvardhangupta5323 dp cannot store negetive indexes
@surajbaranwal56.
@surajbaranwal56. Жыл бұрын
leetcode qn
@rickk3300
@rickk3300 Жыл бұрын
I also have this same doubt
@cooltomcatty
@cooltomcatty Ай бұрын
Beautiful Explanation!!! Kudos!!
@nitishverma1484
@nitishverma1484 Жыл бұрын
Its a suggestion, If you could explain the need of the array as you explained it in this video , in DP-14 video , as I was very confused as to what those T/F represent till end. Now it gets cleared here. I have traced the whole array for that and also that arr[0]
@amartyagupta9922
@amartyagupta9922 Жыл бұрын
arr[0]
@ObitoXuchiha942
@ObitoXuchiha942 Жыл бұрын
We can have only sum/2+1 columns in our DP array. It also worked else it was giving TLE for 1 case. Love this playlist ❤❤
@himansh4812
@himansh4812 Жыл бұрын
Yes. Only columns till totalsum/2 is required.
@meerapanchal8258
@meerapanchal8258 5 ай бұрын
For those who are having 49/50 testcase passing on coding ninjas iterate the inner loop upto target/2 and while calculating minimum absolute difference, iterate loop from target/2 to 0 and as soon as you get first true value break the loop (maximum the target value when dp[n-1][target] is true , minimum the absolute difference)
@neelulalchandani7429
@neelulalchandani7429 5 ай бұрын
thanks this helped.
@parasjaggi268
@parasjaggi268 2 жыл бұрын
understood i tried earlier i made recursion but wasn't able to make it to dp ,,,,,,,,,thanks for making it easy
@vinayprakash1687
@vinayprakash1687 10 ай бұрын
Thanks. I feel if I got this question without knowing about previous question (partition equal subset sum), I would solve it differently. 1. Set target = sum(arr)// 2 2. Try to subtract all the array elements such that the target becomes 0 or atleast the distance from 0 is minimum. In other words, try to find maximum sum using the elements such that it is
@advaitbajaj4241
@advaitbajaj4241 7 ай бұрын
Even I thought of the same way but am unable to code it this way. Could you please provide me the code?
@hemasaijammana5658
@hemasaijammana5658 2 жыл бұрын
This is the same question I was asked in yesterday's interview. I came with recursive and then tried of memoization. After memoization it is giving me TLE, now I am watching this video
@pawanagrawal7653
@pawanagrawal7653 2 жыл бұрын
in which company..?
@spytonic4171
@spytonic4171 2 жыл бұрын
do you use recursion??
@SuryanshKumarPathak-m8o
@SuryanshKumarPathak-m8o Жыл бұрын
As always, great video. Thanks for the explanation Striver. Two points - 1. Rather than finding minimum for every single element, we can run a loop starting from the middle element till 0, and return the first value where dp[n-1][i] == true. 2. How can a problem be solved where the array can contain negative numbers?
@sumitkumartah2106
@sumitkumartah2106 9 ай бұрын
just sort the array
@adi_7861
@adi_7861 2 жыл бұрын
How we can make it work if array contains negative elements as well?
@anshumansharma2251
@anshumansharma2251 2 жыл бұрын
meet in the middle or binary search
@gnanaphanideep6398
@gnanaphanideep6398 Ай бұрын
understood! Thank you for the explanation.
@sannareddymonesh7598
@sannareddymonesh7598 2 жыл бұрын
This problem is entirely depending upon the total sum of array . What if the total sum of array is negative. Then we cannot create negative size dp array
@balakrishnanr648
@balakrishnanr648 Жыл бұрын
in LC its that way
@softwarefoodiee
@softwarefoodiee Жыл бұрын
Sum cannot be negative sunce its mentioned that all the elements are non-negative.
@surya4193
@surya4193 Жыл бұрын
thanks striver,I am able to improve my coding skills the main reason is you and your way of teaching
@Pavankumar-ck5ot
@Pavankumar-ck5ot 2 жыл бұрын
Understood. I think if we declare dp array of size [n][total sum/2+1] will also work.
@takeUforward
@takeUforward 2 жыл бұрын
Yes works
@ntgrn-pr5yx
@ntgrn-pr5yx 20 күн бұрын
understood , thank you striver
@prateeksharma3698
@prateeksharma3698 2 жыл бұрын
If negative elements are also present in given array then what will be maxSum ?
@sageoustheory1957
@sageoustheory1957 2 жыл бұрын
did u find the ans ?
@hrithikm.6619
@hrithikm.6619 Жыл бұрын
Slightly different logic where I'm directly trying to find the subset having the sum as close as possible to sum/2. #include int recursion(int ind, int target, vector& arr,vector &mem) { if(target == 0) return 0; if(ind < 0) return target; if(mem[ind][target] != -1) return mem[ind][target]; int not_pick = recursion(ind-1,target,arr,mem); int pick = INT_MAX; if(target >= arr[ind]) pick = recursion(ind-1,target-arr[ind],arr,mem); return mem[ind][target] = min(pick,not_pick); } int minSubsetSumDifference(vector& arr, int n) { //taking the total_sum int sum = 0; for(auto it : arr) sum+= it; vector mem(n,vector(sum/2 + 2,-1)); //memoization int call = 0; if(sum%2 == 0) { call = recursion(n-1,sum/2,arr,mem); return 2*call; } else { call = recursion(n - 1, (sum / 2) + 1, arr,mem); return abs((2 * call) - 1); } }
@ShubhamKumar-vp4pu
@ShubhamKumar-vp4pu 2 жыл бұрын
Hey striver, I have understood the concept but can we solve it using recursion ?
@sjsjdsbsjjwjs2659
@sjsjdsbsjjwjs2659 2 жыл бұрын
public class Solution { public static int minSubsetSumDifference(int[] nums, int n) { // Write your code here. int sum=0; for(int x:nums) sum+=x; int res=Integer.MAX_VALUE; for(int i=0;i
@prakharsoni7621
@prakharsoni7621 2 жыл бұрын
Yes by adding this... for(int i=s;i>=0;i--) f(dp,n-1,i,arr); Your dp Array now fill perform the operation now :)
@harisrashid0773
@harisrashid0773 2 жыл бұрын
yes we can but will give tle ;
@pranchalsharma2647
@pranchalsharma2647 Жыл бұрын
We need to look at the constraints here because this only works for positive integer array and not when negative numbers are in the array.
@PANKAJKUMAR-oy1hh
@PANKAJKUMAR-oy1hh 2 жыл бұрын
i solved by finding value closer or equal to the half of total sum. but, i feel ur approach is more clear and concise.
@sameerbilla515
@sameerbilla515 2 жыл бұрын
I did same, but cannot memoize it.. can you please tell how can I memoize it
@rohankar5604
@rohankar5604 3 ай бұрын
Understood, great explanation !!!
@maneeshapanu
@maneeshapanu Жыл бұрын
This code now is giving tle with one test case.
@vedantojha766
@vedantojha766 Жыл бұрын
Yes
@chanchalroy3417
@chanchalroy3417 10 ай бұрын
Just because of the previous lectures I was able to solve this problem without watching this lecture. Take a bow... Understood ❤
@jeet7000
@jeet7000 Жыл бұрын
here's my recursive solution class Solution{ public: int ans=1e8; int solve(int i,int arr[],int sum,int curr,int n,vector& dp){ if(i==n){ ans=min(ans,abs(curr-sum)); return ans; } if(sum
@shadab9764
@shadab9764 10 ай бұрын
Thanks man!
@superiors2817
@superiors2817 5 ай бұрын
Hi sir, your explanation of this problem was excellent. But I am facing a problem. In your updated DSA sheet, the given problem link is of leetcode. There, there are different constraints (basically negative numbers). Kindly also explain how to handle negative numbers (since negative indices are not possible, hence this solution won't work)
@shashanksinghal8395
@shashanksinghal8395 29 күн бұрын
We don’t need to fill the complete dp table up to totsum, we can fill up to totsum/2. It will be much more efficient
@hashcodez757
@hashcodez757 3 ай бұрын
"UNDERSTOOD BHAIYA!!"
@vinaykumarratnala5832
@vinaykumarratnala5832 Жыл бұрын
I have solved this question before watching this video only based on the concepts applied in all prev videos. thank you so much
@Swiftie13498
@Swiftie13498 Жыл бұрын
Understood !This series is just insane.I've never understood dp this much easily.Striver you are god level person.Period.
@rahulgyawali
@rahulgyawali 8 ай бұрын
Great Explaination! What if array contains negative numbers? Store indexing can be challenging.
@gouravkrroy3625
@gouravkrroy3625 2 жыл бұрын
The same problem with sorted array becomes book allocation problem?.....if yes then the tc would be nlogn+nlogn and space would be o(1)?....just random thought ! Correct me please if wrong!
@chamanjain9843
@chamanjain9843 Жыл бұрын
28:22 line no 9 if(arr[0]
@shauryatomer1058
@shauryatomer1058 Ай бұрын
thanks again for this awesome tutorial
@likithgullapudi2275
@likithgullapudi2275 Жыл бұрын
used hashing(to store decimal values ) used normal recursion approach from typing import List def minSubsetSumDifference(arr: List[str], n: int) -> int: def fun(i,j): if (i,j) in temp: return temp[(i,j)] if j=0: return min(j,j-arr[0]) else: return j notake=fun(i-1,j) if arr[i]
@likithgullapudi2275
@likithgullapudi2275 Жыл бұрын
made sum to even numbers so that we can do normlaly from typing import List def minSubsetSumDifference(arr: List[str], n: int) -> int: for i in range(len(arr)): arr[i]=2*arr[i] temp=[[-1 for i in range(sum(arr)+1)] for _ in range(len(arr)+1)] #print(temp) def fun(i,j): #print(i,j) if temp[i][j]!=-1: return temp[i][j] if j=0: return min(j,j-arr[0]) else: return j notake=fun(i-1,j) if arr[i]
@tanazshaik678
@tanazshaik678 8 күн бұрын
2 mins of silence for how my brain just stopped in shock when solved this hard problem in a way that my mind processed.
@HarshKumar-ip5nr
@HarshKumar-ip5nr Жыл бұрын
Meet in the middle approach is needed for solving this question on LeetCode. I did every thing but ultimately had to switch to that. Reason being, the leetcode question asked to divide the array into two equal parts, so can't be done using dp. Anyway the code till here is: class Solution { private: long long min(long long a, int b){ if(a>b)return b; return a; } long long minl(long long a, long long b){ if(a>b)return b; return a; } public: int minimumDifference(vector& arr) { long long n = arr.size(); long long mini=INT_MAX; long long totSum=0; for (long long i = 0; i < n; i++) { mini=min(mini, arr[i]); } for (long long i = 0; i < n; i++) { arr[i]-=mini; } for (long long i = 0; i < n; i++) { totSum += arr[i]; } vector < bool > prev(totSum + 1, false); prev[0] = true; if (arr[0] cur(totSum + 1, false); cur[0] = true; for (long long target = 1; target
@dank7044
@dank7044 Ай бұрын
It can be done by DP but i will give TLE.
@BhaskarDev-ll8hv
@BhaskarDev-ll8hv 4 ай бұрын
this will work only for all positive elements or negative elements for mixture of both an algorithm called "meet in the middle" will be used
@_ArjitKhare
@_ArjitKhare Жыл бұрын
Amazing Turned a question into a tool
@harshpratapsingh1638
@harshpratapsingh1638 2 жыл бұрын
you really make this question a piece of cake
@Rahul-ls4ju
@Rahul-ls4ju Жыл бұрын
Understood. Another approach which I thought was to find S1 such that it is nearest to totalsum/2. THis could be done by map or simply by loop. Then could find S2 and hence S2-S1
@riyakumari8377
@riyakumari8377 Жыл бұрын
i thought of same but cant code it properly! :(
@xyz956
@xyz956 Жыл бұрын
​@@riyakumari8377 int rec(vector &arr, vector &bucket, int index, int sum) { if (bucket.size() == arr.size()/2) { // for ( int i =0 ; i
@daniyalhussain5231
@daniyalhussain5231 Жыл бұрын
Why cannot I think of such solutions LoL!!!! Amazing Job!!!
@jaydevkundu554
@jaydevkundu554 Жыл бұрын
Able to solve with just starting hints of 5min.. Thank you striver.. ❣
@atmaramkambli7800
@atmaramkambli7800 Ай бұрын
1st half of video, I was like why we're learning subset equal to k tabulation, 2nd half of video, I am saying "The Legend Striver"
@prabhakaran5542
@prabhakaran5542 8 ай бұрын
Understood ❤
@shubhambalodhi6485
@shubhambalodhi6485 9 ай бұрын
similar question leetcode 1049 -> last stone weight II
@rutwikmore7462
@rutwikmore7462 5 ай бұрын
Explained beautifully ♥
@sangeethagopalan301
@sangeethagopalan301 5 ай бұрын
Greatly simplified!! Understood!!!!
@madhurgupta4220
@madhurgupta4220 2 жыл бұрын
Very Good Explanation. Understood. I think this will be more than enough
@sooyashjaju4208
@sooyashjaju4208 Жыл бұрын
Very much Intuitive ✨
@lol_iris237
@lol_iris237 Жыл бұрын
for java, convert the string to char array instead of using .charAt, the code will be 3 times faster
@parthsalat
@parthsalat 2 жыл бұрын
Understood Kaka! Enjoy your stay at Warsaw!
@rishabhbajpai6234
@rishabhbajpai6234 2 жыл бұрын
understood ..........thanks for doing gret work sir
@abhishekjhanji3014
@abhishekjhanji3014 2 жыл бұрын
"Understood" ....Guess what I coded this problem with a different approach and my score is 100 in this problem of """DP""" ....It's amazing to solve DP ..Thanks bhaiya .... My code here using memoization.. int findans(int a,int t_sum,vector&arr,int i,int &min_v,vector&dp){ if(i
@AmanKumar-fl5ws
@AmanKumar-fl5ws 2 жыл бұрын
was looking for this !!
@the_duskyindiangirl
@the_duskyindiangirl 4 ай бұрын
This approach fails when you have negative numbers in index 0. prev[arr[0]] = true throws index out of bound exception when arr is [-36, 36]. This is a leetcode test case.
@mohitsingal6567
@mohitsingal6567 2 ай бұрын
you can improve it in target loop we are running it till k (total sum) but in s1 loop we are running it till k/2 we know that k is acheivable but are goal is not to find k acheivabe or not we only need it till half way so we run the target loop till half(k/2) since it is going to repeat hope u understood and guys worry not just keep working dp is tricky it will take some time just dont leave
@paveshkanungo6338
@paveshkanungo6338 Жыл бұрын
Understood! Thank you Striver
DP 17. Counts Subsets with Sum K | Dp on Subsequences
36:57
take U forward
Рет қаралды 226 М.
How To Choose Mac N Cheese Date Night.. 🧀
00:58
Jojo Sim
Рет қаралды 40 МЛН
У вас там какие таланты ?😂
00:19
Карина Хафизова
Рет қаралды 26 МЛН
The Singing Challenge #joker #Harriet Quinn
00:35
佐助与鸣人
Рет қаралды 35 МЛН
DP 18. Count Partitions With Given Difference | Dp on Subsequences
18:00
DP 50. Minimum Cost to Cut the Stick
30:02
take U forward
Рет қаралды 144 М.
DP 20. Minimum Coins | DP on Subsequences | Infinite Supplies Pattern
34:15
DP 15. Partition Equal Subset Sum | DP on Subsequences
9:43
take U forward
Рет қаралды 220 М.
DP 13. Cherry Pickup II | 3D DP Made Easy | DP On Grids
43:23
take U forward
Рет қаралды 241 М.
How To Choose Mac N Cheese Date Night.. 🧀
00:58
Jojo Sim
Рет қаралды 40 МЛН