DP 21. Target Sum | DP on Subsequences

Поделиться
HTML-код
  • Опубликовано: 10 фев 2022
  • Lecture Notes/C++/Java Codes: takeuforward.org/dynamic-prog...
    Problem Link: bit.ly/3swy5uL
    Pre-req for this Series: • Re 1. Introduction to ...
    a
    Make sure to join our telegram group for discussions: linktr.ee/takeUforward
    Full Playlist: • Striver's Dynamic Prog...
    In this video, we solve the problem of the target sum. This problem is the eighth problem on DP on the Subsequences Pattern. Please watch DP 18 before watching this.
    If you have not yet checked our SDE sheet, you should definitely do it: takeuforward.org/interviews/s...
    You can also get in touch with me at my social handles: linktr.ee/takeUforward

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

  • @vedanshbhardwaj6548
    @vedanshbhardwaj6548 2 года назад +16

    damn man ! been watching all the videos of this playlist from the beginning, this is the best video so far !! and you striver. You are not only teaching how to do DP, but indeed how to think DP ! Kudos to you for this playlist.

  • @nilimsankarbora5911
    @nilimsankarbora5911 7 месяцев назад +1

    Damn man ! been watching all the videos of this playlist from the beginning, this is the best video so far !! and you Striver. You are not only teaching how to do DP, but indeed how to think DP ! Kudos to you for this playlist.💌💌💌💌

  • @sarthakkumar856
    @sarthakkumar856 2 года назад +48

    I would have never thought, it can also be solved like this🤯. Thanks for this awesome playlist striver❤

  • @johncenakiwi
    @johncenakiwi 2 года назад +18

    I would have never thought of approaching this problem this way. Superb!
    Thanks for this. I have watched and solved all the videos till now in this series.
    Longest Common Subsequence and Longest Increasing Subsequence are much awaited.

  • @sagarmittal1898
    @sagarmittal1898 2 года назад +100

    You will be further directed to DP-17 when you watch DP-18 . This series is very well designed !

    • @immortal6978
      @immortal6978 9 месяцев назад +15

      Its Recursion Go back and complete the part to get answer.
      Higher Problem to lower subproblems

    • @solitucedagar4298
      @solitucedagar4298 24 дня назад

      @@immortal6978 🤣

  • @shushant1847
    @shushant1847 Месяц назад +2

    as soon as you wrote those S1 and S2 i figured out ohh hell yess this can be done by that approach! Best one till now!

  • @subhajitdey135
    @subhajitdey135 4 месяца назад +8

    Before watching your tutorial , I did solve this problem 🙂 using map(the naive recursive way and optimized with map). Here's the solution :
    int f(int i, int target, vector& nums,
    unordered_map& dp) {
    if (i == nums.size()) {
    if (target == 0)
    return 1;
    return 0;
    }
    string key = to_string(i) + "_" + to_string(target);
    if (dp.find(key) != dp.end())
    return dp[key];
    int ways = f(i + 1, target - nums[i], nums, dp) +
    f(i + 1, target + nums[i], nums, dp);
    dp[key] = ways;
    return ways;
    }
    int findTargetSumWays(vector& nums, int target) {
    unordered_map dp;
    return f(0, target, nums, dp);
    }

  • @anything_jara_hatke5237
    @anything_jara_hatke5237 2 года назад +23

    Completed till here, please upload more videos. Thank you for such a quality content.

  • @Rohit-zk1lz
    @Rohit-zk1lz Год назад +14

    plus minus way.
    int solve(int ind,int target,vector &nums,map &dp)
    {


    if(ind < 0)
    {
    //either you achieve the target or you don't achieve the target
    if(target == 0)
    return 1;
    else
    return 0;
    }
    if(dp.find({ind, target}) != dp.end())
    {
    return dp[{ind,target}];
    }
    int plus = 0;
    int minus = 0;
    plus = solve(ind-1,target + nums[ind],nums,dp);
    minus = solve(ind - 1, target - nums[ind],nums,dp);
    return dp[{ind, target}] = plus + minus;

    }
    int findTargetSumWays(vector& nums, int target) {
    map dp;
    return solve(nums.size()-1,target,nums,dp);
    }

    • @samnoitall9799
      @samnoitall9799 3 месяца назад +1

      if we use a vector instead of a map it doesnt work can you please tell why

    • @dhruvmohata7528
      @dhruvmohata7528 3 месяца назад

      @@samnoitall9799 because we have a negative values so we can't put them in vector as we cant have -ve indexes

    • @priyanshkumariitd
      @priyanshkumariitd Месяц назад

      ​@@samnoitall9799 negative values

  • @sandeeperukulla498
    @sandeeperukulla498 2 года назад +5

    wow!!!!! awesome explanation, you are gods gift to the coding community🙏🙏🙏🙏🙏

  • @gautham227
    @gautham227 2 года назад +7

    In this question the target value can also be negative so it'll be better to take the min of sum+ target and sum - target as the length of prev and curr just because of the fact that, if target is negative then sum + target will be smaller than sum - target 😊

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

    I never thought I could solve a dp problem :)...thanks legend!

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

    Damn Damn Damn striver ,was not able to think that this question can be solved using this way.Mapping of problems is very much important.

  • @codecrafts5263
    @codecrafts5263 7 месяцев назад

    Very nice study approaches. Thank you for this.

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

    just fantastic. really getting enjoyed and feeling interested in coding and problem solving after your vidoes and approach sir. Thank you sir

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

    understood bhai , thank you soo much for this entire dp series and all other dsa series as well;

  • @akshayaashok8794
    @akshayaashok8794 15 дней назад +1

    😮😮😮Watching this solution made me go waahh!!!! Thank you bhaiya!!

  • @AlokLaha-te2pd
    @AlokLaha-te2pd 28 дней назад

    Thanks striver. I solved this using normal recursion but you helped me to recognise the pattern of this problem.

  • @vaishnavigour5777
    @vaishnavigour5777 2 года назад +11

    for 2:30 to 2:50 you said exactly what everyone was thinking 😂😂

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

    I was just studying from ur previous videos and got new♥️

  • @SelvaArumugam-xq5mf
    @SelvaArumugam-xq5mf 6 месяцев назад

    The thought process is great bruh

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

    You're genius man.
    Understood very well.

  • @tasneemayham974
    @tasneemayham974 10 месяцев назад +1

    BEST TEACHER EVERRRRR!!!

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

    UNDERSTOOD... !
    Thanks striver for the video... :)

  • @shantipriya370
    @shantipriya370 9 месяцев назад

    understood at its best..

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

    Understood. Thankyou Sir

  • @DevashishJose
    @DevashishJose 7 месяцев назад

    understood thank you so much

  • @mahtoji8935
    @mahtoji8935 9 месяцев назад

    chumeshwari explanation bhayia 🥰🥰🥰

  • @AbhishekKumar-cv1dh
    @AbhishekKumar-cv1dh 8 месяцев назад

    Understoood so damn well 🔥🔥🔥🔥

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

    Understood! I appreciate for your amazing explanation!!

  • @preetisahani5054
    @preetisahani5054 9 месяцев назад

    Understood very well

  • @AshutoshSingh-nq5wd
    @AshutoshSingh-nq5wd 2 года назад

    UNDERSTOOD, thank you very much 😍

  • @saumilaggarwal5233
    @saumilaggarwal5233 9 месяцев назад

    did it on my own, thnx

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

    Once again I was able to solve it on my own. Thank you Striver

  • @souravkumar-eb1wz
    @souravkumar-eb1wz 2 года назад +5

    Understood bro ✌✌ and once again the power of observation is shown 🤩🔥🔥

  • @chanchalroy3417
    @chanchalroy3417 7 месяцев назад

    Incredible 😮

  • @vivekreddy820
    @vivekreddy820 6 месяцев назад

    amazing understood

  • @manyagarg-xz2fr
    @manyagarg-xz2fr Год назад +1

    I solved this problem yesterday and by considering +,- combinations, definitely had space complexity problems. This video gave me a different direction to think this same problem. Thank you!

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

      give me recusion solution bro Im unable to do it .

    • @ok-jg9jb
      @ok-jg9jb Год назад +2

      @@gauravpoharkar9797
      f(ind, tar)
      {
      if(ind==0)
      if(tar+a[0]==0||tar-a[0]==0)
      Return 1
      Else
      Retun 0
      Plus=f(ind-1, a[ind]+tar)
      Minus=f(ind-1, a[ind]-tar)
      Return plus+minus

    • @siddharth892
      @siddharth892 6 месяцев назад

      @@gauravpoharkar9797 For the recursion + Memoisation I think a better way would be to use a dictionary rather than the array because of the negative indexes specially in python since It will start indexing from the back.

  • @MukeshKumar-cc3uh
    @MukeshKumar-cc3uh 4 месяца назад

    Nice! Understood ❤.

  • @paritoshsingh588
    @paritoshsingh588 2 года назад +18

    Omg i made this problem for Coding ninjas

  • @abhishekm385
    @abhishekm385 Месяц назад

    understood!!

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

    What will be the base case for target as there target can be -1000 to 1000 so how he handles the negative values

  • @Parthj426
    @Parthj426 Месяц назад

    UNDERSTOOOOOOD.

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

    Pure genius 👌

  • @farhattasnim8856
    @farhattasnim8856 Месяц назад

    understood!!😀😀😀

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

    understood , outstanding explanation on this video !

  • @prabhakaran5542
    @prabhakaran5542 5 месяцев назад +1

    Understood ❤

  • @himanshukhurana9357
    @himanshukhurana9357 7 месяцев назад

    understood!

  • @googleit2490
    @googleit2490 8 месяцев назад

    Revision done.
    Was confused in the beginning: I had falsely assumed elements to be negative and thus took time to get to the point.
    Nov'13, 2023 05:25 pm

  • @nithishlelll9664
    @nithishlelll9664 7 месяцев назад

    Understood!!😇

  • @kunalkumar1964
    @kunalkumar1964 5 месяцев назад

    Understood!

  • @harshthakur2218
    @harshthakur2218 2 месяца назад +1

    s1-s2=target , man striver is the guyyy!!!!

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

    understood , you are the best teacher

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

    Kudos to your intuition thanks striver

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

    it becomes complicated when there are 0s in input arrays. because they can go to any of two subsets.

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

      I think just returning 2 in case of 0 would work

  • @UECAshutoshKumar
    @UECAshutoshKumar Месяц назад +1

    Thank You
    Understood!

  • @lapimpale
    @lapimpale 2 года назад +4

    Bro, this time understood the ""problem"" more clearly than solution :D. I read somewhere that understanding the problem well is like problem half solved. You are explaining same in multiple ways. I remember the same incidence from Codestudio contest from last week.

    • @ka.patelhimeyatulkumar19ba58
      @ka.patelhimeyatulkumar19ba58 2 года назад

      bhaiyaa aap hai naa aditya verma ka dekhiye acche se samjaya hai. mast hai.

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

      @@ka.patelhimeyatulkumar19ba58 free me ad? Me Jo bola wo samajho pehle fir advice dena

  • @aruna5869
    @aruna5869 5 месяцев назад

    understood :)❤

  • @khushiagarwal7821
    @khushiagarwal7821 Месяц назад

    Understood!!

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

    Understood, sir. Thank you very much.

  • @NARUTOUZUMAKI-bk4nx
    @NARUTOUZUMAKI-bk4nx 7 месяцев назад

    Understoood

  • @user-st9ff2vh6l
    @user-st9ff2vh6l Год назад

    Understood Thanks you so much!

  • @theresilientpianist7114
    @theresilientpianist7114 27 дней назад

    Superb yarrrrrrrr

  • @kathanvakharia
    @kathanvakharia Год назад +1

    Understood...Completed (21/56)

  • @GungunRamchandani
    @GungunRamchandani 29 дней назад

    MindBlowingggggg

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

    UNDERSTOOD

  • @srinathv1412
    @srinathv1412 6 месяцев назад

    Understood !!!!!

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

    Please make a vedio on binary lifting algorithm for kth ancestor in BT. Not much is available on RUclips.
    Thanks in advance. 🙏🙏

  • @asyedmohammedtaha3819
    @asyedmohammedtaha3819 Месяц назад

    genius !!!

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

    understood very well❤❤❤

  • @pallavenkatasai8941
    @pallavenkatasai8941 6 месяцев назад

    Wow it’s a tricky approach

  • @shresthjain7557
    @shresthjain7557 2 месяца назад

    awesome

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

    why totsum-d should be even, incase of odd directly return false?

  • @Piyush-yp2po
    @Piyush-yp2po 9 месяцев назад

    negative positive soln
    f(idx, tar):
    //base case:-
    if(idx==0)
    if(arr(idx)+tar == 0 || arr(idx)-tar == 0) return 1;
    // logic and recursive call
    int neg = f(idx-1, tar - (-arr(i)));
    int pos = f(idx-1, tar - arr(i));
    return neg+pos;
    Time complexity: O(2^N) as every element has 2 options either positive or negative

  • @verma_jay
    @verma_jay 9 месяцев назад

    understood

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

    Understood, thanks!

  • @immortal6978
    @immortal6978 9 месяцев назад

    Understood !!'

  • @krishnavamsiyerrapatruni5385
    @krishnavamsiyerrapatruni5385 4 месяца назад

    Understood :)
    ...

  • @anshul5533
    @anshul5533 2 года назад +4

    Striver bhaiya i was nnot able to comment in last vedio. I was saying that in DP-20 we can do further optimizations too as we have done in 0/1 knapsack by just using a single array reducing the SC to O(target+1)

  • @JoyBoy_013
    @JoyBoy_013 Месяц назад +1

    Understood

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

    int[] a = {1,2,3,1} target = 3
    private static int getCount1(int[] a, int target, int length) {
    if(target == 0){
    return 1;
    }
    if(length == -1 ){
    return 0;
    }
    int pos = getCount1(a, a[length]-target, length-1);
    int neg = getCount1(a, -a[length]-target, length-1);
    return neg + pos;
    }
    with this code I am able to solve the pblm
    but if i try to apply memoization in this dp[arr.length][target+1]
    then there is a pblm where target can go in negative. (-4, -1, -2....) so will get ArrayIndexOutOfBounds -4 for dp[length][target] .
    any idea how to solve this kind of pblms

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

      for such cases you need double the size of the arr

  • @026harshagarwal9
    @026harshagarwal9 2 года назад +1

    Striver bhaiya "Maximum profit in Job Scheduling" waala question explain kijiyegaa na and DP+Binary Search type waale questions explain kijiyegaa naa.
    Thanks for DP series!!

  • @deepanshuthakur140
    @deepanshuthakur140 3 месяца назад

    great

  • @namanchandak1532
    @namanchandak1532 Год назад +7

    this is also solution for the same
    class Solution {
    public:
    int sol(vector& nums, int target,int ind,int curr)
    {
    if(ind==0)
    {
    if(target==curr && nums[0]==0)
    return 2;
    if(target==curr+nums[0] || target==curr-nums[0] )
    return 1;
    return 0;
    }

    int pos=sol(nums,target,ind-1,curr+nums[ind]);
    int neg=sol(nums,target,ind-1,curr-nums[ind]);
    return pos+neg;
    }
    int findTargetSumWays(vector& nums, int target) {
    int n=nums.size();
    // vector
    return sol(nums,target,n-1,0);
    }
    };

    • @aayushbisht4307
      @aayushbisht4307 Год назад +2

      thanks man! I was missing this return condition

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

      @@aayushbisht4307 bruh what will be memorization matrix size

    • @naveenramadheni2482
      @naveenramadheni2482 Год назад +1

      @@shivasai7707 May be memorization is not possible becoz curr will go to negative in some recursive calls

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

      @@naveenramadheni2482 We can memoize it using unordered_map, instead of a 2d vector, use vector

    • @naveenramadheni2482
      @naveenramadheni2482 Год назад +1

      @@GoldyAwad Bro that idea is really good bro. (now got it that how to memoize -ve indexes)

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

    Understood, thanks

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

    Hi..Can you tell that are there cases where memorization will give TLE but not tabulation?

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

      In memoization we basicaaly use recussion to call function right,
      So when we perform calls then we need to ressign variables for each call and calling each function takes a lot more time.
      so memo o(n) >> tab o(n) Always
      Just because of function calls it takes more time.

  • @omop5922
    @omop5922 Год назад +2

    Target is negative here too. Run time error nhi dega?

  • @sangdilbiswal30
    @sangdilbiswal30 27 дней назад

    terminate called after throwing an instance of 'std::length_error'
    what(): cannot create std::vector larger than max_size()
    I am gettting this error in leet code

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

    Can anyone correct my solution:
    int f(int i,int t,vector&arr){
    if(i==0){
    if(abs(t)==arr[0])return 1;
    else return 0;
    }

    int neg=f(i-1,t+arr[i],arr);
    int pos=f(i-1,t-arr[i],arr);
    return neg+pos;
    }
    int targetSum(int n, int target, vector& arr) {
    return f(n-1,target,arr);
    }
    it is going wrong when arr starts with 0.But I dont know y and how to rectify this.

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

    Awesome observation

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

    Understood!❤

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

    plus + negative method of recursion is not working by my code, can anyone let me know the code of it

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

    Eagerly waiting for the next video bro🙏

  • @nookalareshwanth1785
    @nookalareshwanth1785 Месяц назад

    Big Brain...

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

    can anyone pls help me? I am using the recursive approach , where I am either adding the current element to sum or subtracting the current element. and returning 1 when target == sum
    this is the approach:-
    int help(int n,int target,int sum ,vector&arr){
    if(target == sum){
    return 1;
    }
    if (n == 0){
    return 0;
    }
    int ans = help(n-1,target,sum - arr[n - 1],arr);
    ans += help(n - 1,target,sum + arr[n-1],arr);
    return ans;
    }
    int targetSum(int n, int target, vector& arr) {
    return help(n,target,0,arr);
    }
    thanks in advance for the help

  • @anubhavsethi6623
    @anubhavsethi6623 8 месяцев назад

    target = abs(target) can be used to solve it using iterative dp.

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

    Hey Striver, In problem: L3. Longest Word With All Prefixes | Complete String | Trie in Trie Series, you gave c++ solution in java solution link. Can you please provide java solution?

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

    amazing series

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

    Before watching this video I was solving through + - method...It took hell lot of space to tabulate.......After watching video...I was shocked It was the same as S1-s2 = d ...
    #UNDERSTOOD

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

      I think it is not even possible to memoize or tabulate in that way because the range of target is not fixed due to possibility of negative integer, unless you take the max possible sum space on either sides. Please correct me if I am wrong.

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

      @@vinayakgandhi5690 Yes I was taking range as max positive and max negative

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

      @@vinayakgandhi5690 we can also use map instead of 2d matrix

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

    UNDERSTOOD 😊