DP 21. Target Sum | DP on Subsequences

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

Пікірлер: 556

  • @sagarmittal1898
    @sagarmittal18982 жыл бұрын

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

  • @immortal6978

    @immortal6978

    8 ай бұрын

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

  • @solitucedagar4298

    @solitucedagar4298

    16 күн бұрын

    @@immortal6978 🤣

  • @sarthakkumar856
    @sarthakkumar8562 жыл бұрын

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

  • @vedanshbhardwaj6548
    @vedanshbhardwaj65482 жыл бұрын

    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
    @nilimsankarbora59116 ай бұрын

    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.💌💌💌💌

  • @johncenakiwi
    @johncenakiwi2 жыл бұрын

    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.

  • @subhajitdey135
    @subhajitdey1354 ай бұрын

    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); }

  • @shushant1847
    @shushant1847Ай бұрын

    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!

  • @Rohit-zk1lz
    @Rohit-zk1lz11 ай бұрын

    plus minus way. int solve(int ind,int target,vector &nums,map &dp) { if(ind { //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 ай бұрын

    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

    26 күн бұрын

    ​@@samnoitall9799 negative values

  • @anything_jara_hatke5237
    @anything_jara_hatke52372 жыл бұрын

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

  • @vaishnavigour5777
    @vaishnavigour57772 жыл бұрын

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

  • @AlokLaha-te2pd
    @AlokLaha-te2pd19 күн бұрын

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

  • @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.

  • @sandeeperukulla498
    @sandeeperukulla4982 жыл бұрын

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

  • @gautham227
    @gautham2272 жыл бұрын

    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
    @akhildonthula616010 ай бұрын

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

  • @akshayaashok8794
    @akshayaashok87946 күн бұрын

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

  • @codecrafts5263
    @codecrafts52637 ай бұрын

    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
    @sanketkale18512 жыл бұрын

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

  • @SelvaArumugam-xq5mf
    @SelvaArumugam-xq5mf6 ай бұрын

    The thought process is great bruh

  • @chandantaneja6388
    @chandantaneja63882 жыл бұрын

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

  • @sculptandstyle_
    @sculptandstyle_2 жыл бұрын

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

  • @tasneemayham974
    @tasneemayham97410 ай бұрын

    BEST TEACHER EVERRRRR!!!

  • @NirajKumar-nu4lb
    @NirajKumar-nu4lbАй бұрын

    how to modify the memoization solution if the target is negative.??

  • @Hrushi_2000
    @Hrushi_200010 ай бұрын

    Understood. Thankyou Sir

  • @shantipriya370
    @shantipriya3708 ай бұрын

    understood at its best..

  • @paritoshsingh588
    @paritoshsingh5882 жыл бұрын

    Omg i made this problem for Coding ninjas

  • @shubhdangwal4190

    @shubhdangwal4190

    4 ай бұрын

    you baited me man kudos to u !

  • @mahtoji8935
    @mahtoji89358 ай бұрын

    chumeshwari explanation bhayia 🥰🥰🥰

  • @varunaggarwal7126
    @varunaggarwal7126 Жыл бұрын

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

  • @sahilbadkul7130
    @sahilbadkul71302 жыл бұрын

    You're genius man. Understood very well.

  • @sangdilbiswal30
    @sangdilbiswal3019 күн бұрын

    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

  • @DevashishJose
    @DevashishJose6 ай бұрын

    understood thank you so much

  • @preetisahani5054
    @preetisahani50549 ай бұрын

    Understood very well

  • @sandeeperukulla498
    @sandeeperukulla4982 жыл бұрын

    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?

  • @googleit2490
    @googleit24908 ай бұрын

    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

  • @saumilaggarwal5233
    @saumilaggarwal52339 ай бұрын

    did it on my own, thnx

  • @AbhishekKumar-cv1dh
    @AbhishekKumar-cv1dh8 ай бұрын

    Understoood so damn well 🔥🔥🔥🔥

  • @manyagarg-xz2fr
    @manyagarg-xz2fr Жыл бұрын

    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

    Жыл бұрын

    @@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.

  • @omop5922
    @omop5922 Жыл бұрын

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

  • @vivekreddy820
    @vivekreddy8206 ай бұрын

    amazing understood

  • @ranasauravsingh
    @ranasauravsingh2 жыл бұрын

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

  • @kazuma0803
    @kazuma08032 жыл бұрын

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

  • @chanchalroy3417
    @chanchalroy34176 ай бұрын

    Incredible 😮

  • @rohandevaki4349
    @rohandevaki4349 Жыл бұрын

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

  • @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.

  • @cinime
    @cinime2 жыл бұрын

    Understood! I appreciate for your amazing explanation!!

  • @UECAshutoshKumar
    @UECAshutoshKumarАй бұрын

    Thank You Understood!

  • @AshutoshSingh-nq5wd
    @AshutoshSingh-nq5wd2 жыл бұрын

    UNDERSTOOD, thank you very much 😍

  • @farhattasnim8856
    @farhattasnim8856Ай бұрын

    understood!!😀😀😀

  • @deepakagrawal7687
    @deepakagrawal76872 жыл бұрын

    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

  • @abhishekm385
    @abhishekm38521 күн бұрын

    understood!!

  • @lapimpale
    @lapimpale2 жыл бұрын

    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

  • @Parthj426
    @Parthj42622 күн бұрын

    UNDERSTOOOOOOD.

  • @namanchandak1532
    @namanchandak1532 Жыл бұрын

    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

    Жыл бұрын

    thanks man! I was missing this return condition

  • @shivasai7707

    @shivasai7707

    Жыл бұрын

    @@aayushbisht4307 bruh what will be memorization matrix size

  • @naveenramadheni2482

    @naveenramadheni2482

    Жыл бұрын

    @@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

    Жыл бұрын

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

  • @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.

  • @MukeshKumar-cc3uh
    @MukeshKumar-cc3uh4 ай бұрын

    Nice! Understood ❤.

  • @shubhammurarka6589
    @shubhammurarka65898 ай бұрын

    if i do this probelm in this way pick or not pick is it wrong? because we have to count the ways to return the given target. int ways(int target, int i, vector& arr) { if (i == 0) { if (target == arr[0]) return 1; return -1; } if (target == 0) return 1; int take = 0; if (target >= arr[i]) { int takeResult = ways(target - arr[i], i - 1, arr); take = (takeResult == -1) ? 0 : 1 + takeResult; } int notTake = 0; int notTakeResult = ways(target, i - 1, arr); notTake = (notTakeResult == -1) ? 0 : 1 + notTakeResult; return take + notTake; }

  • @harshthakur2218
    @harshthakur2218Ай бұрын

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

  • @prabhakaran5542
    @prabhakaran55424 ай бұрын

    Understood ❤

  • @dakshlakhotiya4275
    @dakshlakhotiya42752 жыл бұрын

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

  • @sarthakragwan5248
    @sarthakragwan52482 жыл бұрын

    Pure genius 👌

  • @souravkumar-eb1wz
    @souravkumar-eb1wz2 жыл бұрын

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

  • @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

  • @kunalkumar1964
    @kunalkumar19645 ай бұрын

    Understood!

  • @NARUTOUZUMAKI-bk4nx
    @NARUTOUZUMAKI-bk4nx7 ай бұрын

    Understoood

  • @theresilientpianist7114
    @theresilientpianist711419 күн бұрын

    Superb yarrrrrrrr

  • @dakshmaru5577
    @dakshmaru55776 ай бұрын

    Understood!!

  • @GungunRamchandani
    @GungunRamchandani20 күн бұрын

    MindBlowingggggg

  • @himanshukhurana9357
    @himanshukhurana93576 ай бұрын

    understood!

  • @kathanvakharia
    @kathanvakharia Жыл бұрын

    Understood...Completed (21/56)

  • @pallavenkatasai8941
    @pallavenkatasai89416 ай бұрын

    Wow it’s a tricky approach

  • @aruna5869
    @aruna58694 ай бұрын

    understood :)❤

  • @samyakagarwal1777
    @samyakagarwal1777 Жыл бұрын

    understood , you are the best teacher

  • @shresthjain7557
    @shresthjain7557Ай бұрын

    awesome

  • @shravan9796
    @shravan97962 жыл бұрын

    understood , outstanding explanation on this video !

  • @Piyush-yp2po
    @Piyush-yp2po9 ай бұрын

    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

  • @026harshagarwal9
    @026harshagarwal92 жыл бұрын

    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!!

  • @nithishlelll9664
    @nithishlelll96647 ай бұрын

    Understood!!😇

  • @srinathv1412
    @srinathv14126 ай бұрын

    Understood !!!!!

  • @verma_jay
    @verma_jay9 ай бұрын

    understood

  • @JoyBoy_013
    @JoyBoy_01327 күн бұрын

    Understood

  • @asyedmohammedtaha3819
    @asyedmohammedtaha381923 күн бұрын

    genius !!!

  • @anshul5533
    @anshul55332 жыл бұрын

    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)

  • @takeUforward

    @takeUforward

    2 жыл бұрын

    Yes.

  • @arindamdongre4143

    @arindamdongre4143

    11 ай бұрын

    how?

  • @arindamdongre4143

    @arindamdongre4143

    11 ай бұрын

    I am gettig wrong answer by using only one array

  • @THETRUTH-te2oc
    @THETRUTH-te2oc2 жыл бұрын

    Please bhaiya reply... I am getting a huge tention in my mind about my branch (electrical engineering) in Haldia Institute of Technology that weather my branch will stop my success or do electrical engineering students gets equal opportunity in 'big IT companies'?

  • @p38_amankuldeep75
    @p38_amankuldeep75 Жыл бұрын

    understood very well❤❤❤

  • @ratinderpalsingh5909
    @ratinderpalsingh59092 жыл бұрын

    Understood, sir. Thank you very much.

  • @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

  • @navneetdubey6918
    @navneetdubey69189 ай бұрын

    UNDERSTOOD

  • @immortal6978
    @immortal69788 ай бұрын

    Understood !!'

  • @deepanshuthakur140
    @deepanshuthakur1403 ай бұрын

    great

  • @krishnavamsiyerrapatruni5385
    @krishnavamsiyerrapatruni53854 ай бұрын

    Understood :) ...

  • @user-st9ff2vh6l
    @user-st9ff2vh6l Жыл бұрын

    Understood Thanks you so much!

  • @RahulKumar-sr9cz
    @RahulKumar-sr9cz2 жыл бұрын

    Hii sir! Why this approach is not working in Leetcode's Target Sum problem? Can anyone tell me the memoization approach of leet code's Target sum problem and what is the difference between this and that problem?

  • @abhishekgururani6993

    @abhishekgururani6993

    2 жыл бұрын

    because in leetcode there are test cases in which target is a -ve number.

  • @Steve-kv5we

    @Steve-kv5we

    Жыл бұрын

    It is working fine in leetcode u must have done something wrong.

  • @mohansharma1989

    @mohansharma1989

    Жыл бұрын

    I tried this way in LC public int findTargetSumWays(int[] nums, int target) { Map dp = new HashMap(); return findTargetSumWaysBottomUpMemoization(nums, nums.length - 1, target, dp); } private int findTargetSumWaysBottomUpMemoization(int[] nums, int index, int target, Map dp) { if (index == 0) { if (target == 0 && nums[0] == 0) { return 2; } else if (target + nums[0] == 0 || target - nums[0] == 0) return 1; else return 0; } String key = index + "-" + target; if (dp.containsKey(key)) return dp.get(key); int minus = findTargetSumWaysBottomUpMemoization(nums, index - 1, target - nums[index], dp); int plus = findTargetSumWaysBottomUpMemoization(nums, index - 1, target + nums[index], dp); int count = minus + plus; dp.put(key, count); return count; } But struggling to convert to tabulation

  • @anshumaan1024

    @anshumaan1024

    Жыл бұрын

    this is memoization soln class Solution { public: int f(int ind, int target, vector &nums, vector &dp){ if(ind==0){ if(nums[0]==0 && target==0) return 2; if(target==0 || nums[0]==target) return 1; else return 0; } if(dp[ind][target]!= -1) return dp[ind][target]; int notTake = f(ind-1,target,nums,dp); int take = 0; if(nums[ind]

  • @lavkushdas5529

    @lavkushdas5529

    Жыл бұрын

    @@anshumaan1024 Thanks bro , i was not updating dp matrix according to new target

  • @nookalareshwanth1785
    @nookalareshwanth1785Ай бұрын

    Big Brain...

  • @devanshhalwai9655
    @devanshhalwai96552 жыл бұрын

    Awesome observation

  • @SumitKumar-lu1pv
    @SumitKumar-lu1pv5 ай бұрын

    The only thing that demotivates in dp if somewhere I need to think out of the box and I feel I'm not that smart.

  • @sauravchandra10
    @sauravchandra10 Жыл бұрын

    Understood, thanks!

  • @vamsimadugula8524
    @vamsimadugula8524 Жыл бұрын

    int f(int ind,int target,vector& arr){ if(ind==0){ if(arr[0]==target || arr[0]==(-target)) return 1; return 0; } int plus = f(ind-1,target-arr[ind],arr); int minus = f(ind-1,target+arr[ind],arr); return plus+minus; } Can anyone tell when i convert this into memoization im getting wrong answer. And also i took size of dp array as int sum = 0; for(int i=0;i

  • @shashankkumar5005

    @shashankkumar5005

    11 ай бұрын

    same problem bro

  • @shashankkumar5005

    @shashankkumar5005

    11 ай бұрын

    actually here the target can be negative at any point making dp[index][negative]

  • @gyanp_28

    @gyanp_28

    11 ай бұрын

    Here when we call the function through minus the problem arises because the target can become negative too and the 2-d dp array is working from 0-> target hence it will give index out of bound error One possible solution can be using memoization only when the target>=0 through this we can avoid the error but the code willnt be fully optimised

  • @karthikk2316

    @karthikk2316

    5 ай бұрын

    in the base case add one more condiitoin if(arr[0]==target &&arr[0]==(-target))return 2; before the or used base condition

  • @calderanoadi5982
    @calderanoadi59822 жыл бұрын

    If the target is negative then what should we do ?

  • @pranavm002

    @pranavm002

    Жыл бұрын

    use map as instead of vector as dp map dp;