Minimum subset sum difference | Minimum difference subsets | Dynamic Programming

Поделиться
HTML-код
  • Опубликовано: 16 окт 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

Комментарии • 96

  • @poojabennabhaktula4883
    @poojabennabhaktula4883 3 года назад +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  3 года назад +14

      Looks like I should apply for singing 😂

    • @madhav3444
      @madhav3444 3 года назад +1

      @Andrew Kaison HAHAHA

    • @unsaturated8482
      @unsaturated8482 3 года назад +1

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

  • @souravdey8236
    @souravdey8236 2 года назад +10

    What if negative elements are there?

  • @nagulaabhishek
    @nagulaabhishek 3 года назад +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 3 года назад +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]

  • @adityaojha2701
    @adityaojha2701 3 года назад +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  3 года назад +1

      Nice 👍🏼

    • @suvamroy6205
      @suvamroy6205 3 года назад +2

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

    • @techdose4u
      @techdose4u  3 года назад

      @@suvamroy6205 👍🏼

    • @imajt5
      @imajt5 3 года назад

      I was thinking the same thing @Aditya Ohja

    • @saitejamahankali483
      @saitejamahankali483 3 года назад +2

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

  • @sandeepnallala48
    @sandeepnallala48 3 года назад +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 : )

  • @abhishekjaiswal6492
    @abhishekjaiswal6492 3 года назад +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??

  • @Cloud-577
    @Cloud-577 2 года назад +2

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

  • @renon3359
    @renon3359 3 года назад +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 3 года назад +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 3 года назад

      Yes.... you are correct.

    • @juliahuanlingtong6757
      @juliahuanlingtong6757 3 года назад

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

    • @jitinkrishna790
      @jitinkrishna790 3 года назад +5

      @@avinashjha4887 Space Complexity wont decrease but space will decrease

  • @0anant0
    @0anant0 4 года назад +1

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

  • @iamyuvraj128
    @iamyuvraj128 Год назад

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

    • @techdose4u
      @techdose4u  Год назад

      Thanks for the appreciation :)

  • @fog968
    @fog968 2 года назад +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 2 года назад

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

  • @yeswanthbonagiri7142
    @yeswanthbonagiri7142 4 года назад +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 :)

  • @harish900
    @harish900 Год назад

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

  • @aniketsriwastva6345
    @aniketsriwastva6345 3 года назад +5

    Great explaination sir
    Thank You

  • @FrontendMonk
    @FrontendMonk 3 года назад

    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))?

  • @theghostwhowalk
    @theghostwhowalk 4 года назад +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.

  • @jagadeeshp2558
    @jagadeeshp2558 3 года назад +3

    Nailed it sir 🔥🔥🔥

  • @bhavyabansal1143
    @bhavyabansal1143 2 года назад

    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]

  • @tips_zone
    @tips_zone 2 года назад

    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.

  • @vcs649
    @vcs649 10 месяцев назад

    fantastic explanation

  • @syedkaja2045
    @syedkaja2045 4 года назад +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  4 года назад +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 4 года назад +1

      @@techdose4u thanks sir

    • @techdose4u
      @techdose4u  4 года назад

      Welcome

  • @dhruvbajoria4502
    @dhruvbajoria4502 2 года назад +1

    how deal if array has negative elements

  • @Nikita-hv5jm
    @Nikita-hv5jm 3 года назад

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

  • @anonymous_31045
    @anonymous_31045 Год назад +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

  • @jasonliu3202
    @jasonliu3202 3 года назад +3

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

    • @techdose4u
      @techdose4u  3 года назад

      Yea :)

    • @nemnoton
      @nemnoton 3 года назад +1

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

    • @anshumanpanigrahi7817
      @anshumanpanigrahi7817 3 года назад

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

  • @nemnoton
    @nemnoton 3 года назад

    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,
    ];

  • @labib28
    @labib28 3 года назад +3

    sir u are great....continue

  • @prabhatkashyap8333
    @prabhatkashyap8333 3 года назад +2

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

    • @techdose4u
      @techdose4u  3 года назад

      Yep

    • @prabhatkashyap8333
      @prabhatkashyap8333 3 года назад

      @@techdose4u can you please explain it little bit.

    • @mwshubham
      @mwshubham 3 года назад

      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

  • @priyarathore9266
    @priyarathore9266 3 года назад +1

    Good one!
    Keep it up

  • @vansikagupta5046
    @vansikagupta5046 3 года назад +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

    • @techdose4u
      @techdose4u  3 года назад +1

      Yes. You can store the max amount. Perfectly fine :)

    • @vansikagupta5046
      @vansikagupta5046 3 года назад

      @@techdose4u Thank you :D

  • @iSumitYadav
    @iSumitYadav 4 года назад +1

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

    • @techdose4u
      @techdose4u  4 года назад +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 4 года назад

      @@techdose4u okay, thanks bro 👍🏻

    • @0anant0
      @0anant0 4 года назад +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  4 года назад +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 4 года назад

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

  • @shritishaw7510
    @shritishaw7510 2 года назад

    extraordinary explanation. Keep it up, mate.

  • @dhanashreegodase4445
    @dhanashreegodase4445 2 года назад

    Thanks for video..osssum

  • @ashvinkumhar5819
    @ashvinkumhar5819 2 года назад

    Great work!!!!!!!!!

  • @funvibes001
    @funvibes001 Год назад

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

  • @amitavamozumder73
    @amitavamozumder73 3 года назад

    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

  • @shivambaghel9668
    @shivambaghel9668 3 года назад

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

  • @ManojYadav-ew3wr
    @ManojYadav-ew3wr 2 года назад +1

    this approach is not working for negative numbers

  • @syedkaja2045
    @syedkaja2045 4 года назад +1

    can we fill the dp table using recursion

    • @techdose4u
      @techdose4u  4 года назад

      That's memoization.

    • @syedkaja2045
      @syedkaja2045 4 года назад

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

    • @syedkaja2045
      @syedkaja2045 4 года назад

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

    • @syedkaja2045
      @syedkaja2045 4 года назад

      @@techdose4u why are u not replying sir

  • @gauravsoni2919
    @gauravsoni2919 Год назад

    bro what if the numbers are negative

  • @vanditkhuranapvt
    @vanditkhuranapvt 3 года назад +1

    What if S1 is found after half ?

    • @SM-vg6xk
      @SM-vg6xk 3 года назад

      S1 represents the smaller partition so it has to be

  • @rohandevaki4349
    @rohandevaki4349 Год назад +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

  • @vukanoa
    @vukanoa 11 месяцев назад

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

  • @balutprasad4500
    @balutprasad4500 2 года назад

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

  • @ravindrayadav6103
    @ravindrayadav6103 Год назад

    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 4 года назад

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