Minimum subset sum difference | Minimum difference subsets | Dynamic Programming

Sdílet
Vložit
  • čas přidán 13. 09. 2024
  • This video explains a very important programming interview problem based on dynamic programming in the 01 knapsack category which is to find the minimum subset sum difference.In this problem we need to minimize the difference of sum between 2 subsets which are formed on dividing a set into 2 subsets.The sum 0 will be minimum for all positive numbers when equal sum partition is possible.This problem is very similar to the equal sum partition problem and uses the subset sum problem technique with a little tweak to solve the problem.I have first explained the problem and then showed the intuition by reducing and relating this problem to the already solved subset sum problem.I have shown examples for better understanding and intuition and at the end of the video, I have also shown the code implementation in both Java and C++.
    CODE LINK is present below as usual. If you find any difficulty or have any query then do COMMENT below. PLEASE help our channel by SUBSCRIBING and LIKE our video if you found it helpful...CYA :)
    ========================================================================
    Join this channel to get access to perks:
    / @techdose4u
    INSTAGRAM : / surya.pratap.k
    SUPPORT OUR WORK: / techdose
    LinkedIn: / surya-pratap-kahar-47b...
    WEBSITE: techdose.co.in/
    TELEGRAM Channel LINK: t.me/codewithT...
    TELEGRAM Group LINK: t.me/joinchat/...
    =======================================================================
    CODE LINK: gist.github.co...
    JAVA Code: gist.github.co...
    USEFUL LINKS:
    Subset Sum Problem: • subset sum problem dyn...
    01 Knapsack Tabulation DP: • 01 Knapsack Tabulation...
    Equal Sum Partition: • Partition equal subset...
    Count Subsets with given Sum: • Count subsets with giv...
    #dp #subsetsum #01knapsack

Komentáře • 96

  • @souravdey8236
    @souravdey8236 Před 2 lety +10

    What if negative elements are there?

  • @poojabennabhaktula4883
    @poojabennabhaktula4883 Před 3 lety +12

    You have a great voice which makes us pay detail attention to what you're saying . Thank you for such excellent series. Very engaging!

    • @techdose4u
      @techdose4u  Před 3 lety +14

      Looks like I should apply for singing 😂

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

      @Andrew Kaison HAHAHA

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

      It was so good, I slept while listening to him,
      @pooja gattiga chaduvtav.

  • @adityaojha2701
    @adityaojha2701 Před 3 lety +13

    We can reduce time by creating a dp[n+1][sum/2+1]. Thanks sir, it worked because u explained so well.

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

      Nice 👍🏼

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

      Yes I did it that way too. All thanks goes to sir.

    • @techdose4u
      @techdose4u  Před 3 lety

      @@suvamroy6205 👍🏼

    • @imajt5
      @imajt5 Před 3 lety

      I was thinking the same thing @Aditya Ohja

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

      We can also iterate from backwards i.e. for(int i = sum/2 ; i>=0 ;i--) in the last step.

  • @nagulaabhishek
    @nagulaabhishek Před 3 lety +14

    Firstly, thank you so much for doing these videos. Much appreciated!
    Question:
    Set S is divided to S1, S2. We are calculating only for S1, which is

    • @khalidkhan8292
      @khalidkhan8292 Před 3 lety +11

      yes, by taking dp[n+1][sum/2+1] we can reduce the time complexity. I guess he just wanted to explain in a way everyone understands the concept behind it and that's why he took dp[n+1][sum]

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

    great work sir. for all your videos, before watching till the end, i hit like cz i know it will be awesome and simple to understand : )

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

    a small optimization, instead of constructing N*W array its enough to construct N*ceil(W/2) and check last row from last column and if it's true then min-difference=abs(i-(W-i)) where i is the column index, W is sum, happy coding :)

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

    Great explaination sir
    Thank You

  • @renon3359
    @renon3359 Před 3 lety +11

    Since we are considering that s1 < s2, will it make sense instead of taking the weight range 0 - 11, we just take 0 - 5? Since it seems that at the end we will use the last for column 0 - 5 only?

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

      You are absolutely correct. It would reduce the space complexity as well as the time complexity to half of the original and of course it would still work.

    • @amanverma9829
      @amanverma9829 Před 3 lety

      Yes.... you are correct.

    • @juliahuanlingtong6757
      @juliahuanlingtong6757 Před 3 lety

      This idea came to me too. Was just about to ask and verify

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

      @@avinashjha4887 Space Complexity wont decrease but space will decrease

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

    sir, one thing i didn't understand, we are checking for dp[n][i]==True condition , how can one be sure that dp[n][sum-i] will also be true??

  • @0anant0
    @0anant0 Před 3 lety +1

    Thanks! Very well explained. Knowledge of solving 'Subset sum' (links in desc) is a pre-req for this.

  • @iamyuvraj128
    @iamyuvraj128 Před rokem

    It is not one of the best explanation, but it is the best explanation. Thank you🙏

  • @theghostwhowalk
    @theghostwhowalk Před 3 lety +6

    Thanks for video! I guess it’s tricky to see this as a variation of can we divide the array into 2 equal sum subset question.

  • @Cloud-577
    @Cloud-577 Před 2 lety +2

    What about an array of negative and positive integers. Would dp be able to solve this efficiently?

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

    Nailed it sir 🔥🔥🔥

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

    fantastic explanation

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

    You can use 1D array to do that, no need for 2D tho.

    • @techdose4u
      @techdose4u  Před 3 lety

      Yea :)

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

      How do you go back and look up the true/false values?
      Can you link to any example of this?

    • @anshumanpanigrahi7817
      @anshumanpanigrahi7817 Před 3 lety

      @@nemnoton Just iterate over the last row, by keeping row no. constant.

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

    sir u are great....continue

  • @amitavamozumder73
    @amitavamozumder73 Před 3 lety

    you know you've been watching too many tech dose videos when you know the answer the moment he says "it's a variation of ... problem". LOL thanks

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

    Hi Sir, What if the input contains negative numbers too? I see the solution would not consider negative number in the input array

    • @saurav0203srivastav
      @saurav0203srivastav Před 2 lety

      Exactly what I am trying to find the solution for, I guess in Negative numbers we cant really use this approach

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

    Good one!
    Keep it up

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

    sir,you have explained diff=sum-2s1
    but in the code abs(first-second)
    can we use any of the above statements?
    and overall amazing explanation

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

      In the code I have simplified. If you closely look at first and second then first is S1 and second is (SUM-S1). If you subtract them then it will be (SUM-2*S1). They both are exactly the same.

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

      @@techdose4u thanks sir

    • @techdose4u
      @techdose4u  Před 3 lety

      Welcome

  • @tips_zone
    @tips_zone Před 2 lety

    In the code when you try to find the minimum difference value, you iterate from 0 to sum/2. I its not always the result in the True value that is closest to the sum/2 ?
    i= sum//2
    while not dp[n][i]:
    i-=1
    diff= sum-2*i
    if i is closer to sum/2 the difference is minimized, therefore we only neet to find the column with True value closer to sum/2.

  • @Nikita-hv5jm
    @Nikita-hv5jm Před 3 lety

    thank you so much sir for such a great explanation...really it was very much helpful thanks a lot sir...

  • @shritishaw7510
    @shritishaw7510 Před 2 lety

    extraordinary explanation. Keep it up, mate.

  • @nemnoton
    @nemnoton Před 3 lety

    Thanks for the clarifications and the code example!
    I first got the wrong value, but I did a mistake , if I want to get the two optimal pair of values then I need the "i" value instead of diff, or you can return both the i and diff.
    I use PHP, so it will be:
    $value = 0;
    for ($i=0; $i abs($first-$second)){

    //get value
    $value = $i;
    $diff = abs($first-$second);
    }
    }
    return [
    'value' => $value,
    'diff' => $diff,
    ];

  • @dhanashreegodase4445
    @dhanashreegodase4445 Před 2 lety

    Thanks for video..osssum

  • @harish900
    @harish900 Před rokem

    if nums[i] is negative then how to proceed?..in the leetode qn constraint its negative

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

    how deal if array has negative elements

  • @FrontendMonk
    @FrontendMonk Před 3 lety

    So if we want to solve this question using recursion then we have to apply subset sum solution for 0 to sum/2 and then we have to find the minimum of them after putting them in this formula:- (sum - 2(answer of each subset sum problem))?

  • @bhavyabansal1143
    @bhavyabansal1143 Před 2 lety

    Thank you for the video. For some reason, this code does not work for some inputs like: [76,8,45,20,74,84,28,1]

  • @funvibes001
    @funvibes001 Před rokem

    In case of negative values it will fail as array can not have negative index.

  • @ashvinkumhar5819
    @ashvinkumhar5819 Před 2 lety

    Great work!!!!!!!!!

  • @anonymous_31045
    @anonymous_31045 Před rokem +1

    hey your code is not working on leetcode
    def minimumDifference(self, nums) :
    n = len(nums)
    sum = 0
    for i in range(n):
    sum += nums[i]
    dp = [[False]*(sum+1) for i in range(n+1)]
    for i in range(n+1):
    for j in range(sum+1):
    if j == 0:
    dp[i][j] = True
    elif i == 0:
    dp[i][j] = False
    elif nums[i-1]>j:
    dp[i][j] = dp[i-1][j]
    else:
    dp[i][j] = dp[i-1][j] or dp[i-1][j-nums[i-1]]
    diff = float('inf')
    for i in range(sum//2+1):
    first = i
    second = sum-i
    if dp[n][i] == True and diff>abs(first-second):
    diff = abs(first-second)
    return diff

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

    Firstly thank you very much for this whole DP series. It is extremely helpful. Secondly, I have a small doubt. If I know that my subset S1 can have maximum sum as S/2 only, I can find the maximum sum S1 can have(like max profit in 0/1 knapsack). In that case we will store max sum possible and not T/F in the DP table. Is this approach fine? I solved the interview bit problem like this, but wanted to know from you if thinking this way is fine too

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

    Can you try adding serial numbers to this dp series and make a playlist?
    Thanks 👍🏻

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

      It's already in the playlist and numbering will hamper me from adding new videos randomly and shuffling part. Moreover, those who want to learn just particular videos will not feel comfortable if I number them.

    • @iSumitYadav
      @iSumitYadav Před 3 lety

      @@techdose4u okay, thanks bro 👍🏻

    • @0anant0
      @0anant0 Před 3 lety +3

      @@techdose4u I have a suggestion: Instead of numbering, you can categorize them into DP patterns. e.g. ks-01 from knapsack 0/1, ks-INF (knapsack infinity), Partition (e.g. MCM, eggdrop), etc. so that students can see the similarity in code within a given pattern. Thanks!

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

      @@0anant0 yea. That I am doing. I am covering in order and later when I include more videos then I will insert them in order.

    • @0anant0
      @0anant0 Před 3 lety

      @@techdose4u Thanks! Your videos are very helpful - I watch them everyday :-)

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

    bro, can we do it using int[][] dp not by boolean[][] dp??

    • @techdose4u
      @techdose4u  Před 3 lety

      Yep

    • @prabhatkashyap8333
      @prabhatkashyap8333 Před 3 lety

      @@techdose4u can you please explain it little bit.

    • @mwshubham
      @mwshubham Před 3 lety

      You can use short array as well treat 0 as false and 1 as true. Also we can optimise the solution using 1D tabular dp just like sunset sum. Also solving only till sum/2 is enough

  • @ManojYadav-ew3wr
    @ManojYadav-ew3wr Před 2 lety +1

    this approach is not working for negative numbers

  • @shivambaghel9668
    @shivambaghel9668 Před 3 lety

    Your code will set false at dp[0][0] which is not right , according to the theory part

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

    What if S1 is found after half ?

    • @SM-vg6xk
      @SM-vg6xk Před 3 lety

      S1 represents the smaller partition so it has to be

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

    19th line:
    What if (j - A[i] < 0)?
    We'd get a Segmentation Fault;

  • @gauravsoni2919
    @gauravsoni2919 Před rokem

    bro what if the numbers are negative

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

    can we fill the dp table using recursion

    • @techdose4u
      @techdose4u  Před 3 lety

      That's memoization.

    • @syedkaja2045
      @syedkaja2045 Před 3 lety

      @@techdose4u yes pls explain this method or else just type the code

    • @syedkaja2045
      @syedkaja2045 Před 3 lety

      @@techdose4u pls just type the code sir please :(

    • @syedkaja2045
      @syedkaja2045 Před 3 lety

      @@techdose4u why are u not replying sir

  • @balutprasad4500
    @balutprasad4500 Před 2 lety

    How this is different from leetcode 2035 ?
    Leetcode 2035 : Partition array into two arrays to minimize the difference

  • @rohandevaki4349
    @rohandevaki4349 Před rokem +1

    man , why do you waste others time by putting the solution that doesnt work?? check on leet code, the -36,36 test case is not working

  • @ravindrayadav6103
    @ravindrayadav6103 Před rokem

    why this code gives runtime error-class Solution {
    public:
    int minimumDifference(vector& nums) {
    int sum=0;
    int n=nums.size();
    for(int it:nums){
    sum+=it;
    }
    vectordp(n+2,vector(sum+2));
    for(int i=0;i

  • @tech_wizard9315
    @tech_wizard9315 Před 3 lety

    Please make a roadmap for fresher (batch 2020)to crack google in 6months for a DSA beginner