Maximum Profit in Job Scheduling | Recursion | Memoization | Leetcode 1235

Sdílet
Vložit
  • čas přidán 24. 11. 2022
  • Whatsapp Community Link : www.whatsapp.com/channel/0029...
    This is the 5th Video on our Dynamic Programming Playlist.In this video we will try to solve a good and a classic DP problem - Maximum Profit in Job Scheduling (Leetcode 1235)
    I will explain the intuition so easily that you will never forget and start seeing this as cakewalk EASYYY.
    We will do live coding after explanation and see if we are able to pass all the test cases.
    Also, please note that my Github solution link below contains both C++ as well as JAVA code.
    Problem Name : Maximum Profit in Job Scheduling
    Company Tags : Google, Doordash, Airbnb, Adobe
    My solutions on Github(C++ & JAVA) : github.com/MAZHARMIK/Intervie...
    Leetcode Link : leetcode.com/problems/maximum...
    My DP Concepts Playlist : • Roadmap for DP | How t...
    My Graph Concepts Playlist : • Graph Concepts & Qns -...
    My GitHub Repo for interview preparation : github.com/MAZHARMIK/Intervie...
    Subscribe to my channel : / @codestorywithmik
    Instagram : / codestorywithmik
    Facebook : / 100090524295846
    Twitter : / cswithmik
    Approach Summary : It uses memoization and binary search to maximize total profit by selecting non-overlapping jobs based on start times, end times, and profits. The jobScheduling function initializes, sorts, and calls the solve function, which recursively explores job selection scenarios. The getNextIndex function efficiently finds the index of the next job using binary search. The goal is to return the maximum profit for the given jobs.
    ╔═╦╗╔╦╗╔═╦═╦╦╦╦╗╔═╗
    ║╚╣║║║╚╣╚╣╔╣╔╣║╚╣═╣
    ╠╗║╚╝║║╠╗║╚╣║║║║║═╣
    ╚═╩══╩═╩═╩═╩╝╚╩═╩═╝
    Timelines
    00:00 - Introduction
    #coding #helpajobseeker #easyrecipes #leetcode #leetcodequestionandanswers #leetcodesolution #leetcodedailychallenge #leetcodequestions #leetcodechallenge #hindi #india #coding #helpajobseeker #easyrecipes #leetcode #leetcodequestionandanswers #leetcodesolution #leetcodedailychallenge#leetcodequestions #leetcodechallenge #hindi #india #hindiexplanation #hindiexplained #easyexplaination #interview#interviewtips #interviewpreparation #interview_ds_algo #hinglish #github #design #data #google #video #instagram #facebook #leetcode #computerscience #leetcodesolutions #leetcodequestionandanswers #code #learning #dsalgo #dsa #2024 #newyear

Komentáře • 123

  • @arthurlewin1952
    @arthurlewin1952 Před rokem +23

    Another video another great explanation The way you take us from brute force to optimized solution is phenomenal

  • @souravjoshi2293
    @souravjoshi2293 Před rokem +18

    The man with magical voice.
    Another DP problem made easy. Thank you so much

  • @aws_handles
    @aws_handles Před 6 měsíci +17

    Last year i made a huge mistake of taking a paid course which taught me nothing for my intuition building. This year i will practice on my own and be better at DSA

  • @ugcwithaddi
    @ugcwithaddi Před 6 měsíci +4

    Insane explanation. It doesn’t seem Hard anymore 🔥🙌

  • @sunilsarode152
    @sunilsarode152 Před 2 měsíci +1

    I was stuck on how to find next job and then I saw your video, clean !!

  • @user-ge8cg8yy6n
    @user-ge8cg8yy6n Před 6 měsíci +1

    This is the best question to learn/refresh every crucial concept: sorting, binary search, and dynamic programming. Nicely explained as usual.

  • @wearevacationuncoverers
    @wearevacationuncoverers Před 6 měsíci

    This is the only place I get me doubts answered. Thanks mik sir

  • @ispyu1514
    @ispyu1514 Před rokem +1

    Great explanation!

  • @humanity7880
    @humanity7880 Před 11 měsíci +1

    Thank you for this amazing explanation!

  • @vartikatiwari5203
    @vartikatiwari5203 Před rokem +2

    Great sir,Keep going

  • @keshavmn7283
    @keshavmn7283 Před rokem +1

    Really good explanation 👍

  • @yogeshkumarverma2125
    @yogeshkumarverma2125 Před 8 měsíci +1

    Bhai bohot bohot dhanyawad❤

  • @nadeking1530
    @nadeking1530 Před 6 měsíci +1

    As always awesome explanation , where would we go without you lol!

  • @shoaibakhtar9194
    @shoaibakhtar9194 Před 3 měsíci

    Best and easy explanation of this question

  • @abhinavtomar8518
    @abhinavtomar8518 Před 11 měsíci +3

    Really well explained bro, Doesn't feel it was a hard question. Really impressed the way you explain keep bringing such videos thank you

  • @codeyoga
    @codeyoga Před 6 měsíci

    Good question to apply Binary Search and Recursion with Memo. Very nicely explained, keep it up !

  • @sz.110
    @sz.110 Před rokem +1

    La jawaab ❤‍🔥❤‍🔥❤‍🔥

  • @siriusblack88
    @siriusblack88 Před rokem +1

    Great expectation

  • @amankushwaha8180
    @amankushwaha8180 Před 4 měsíci +1

    your explanation are very good

  • @deepakdass4710
    @deepakdass4710 Před 6 měsíci

    Thanks sir for great explanation ❤❤

  • @nisarggogate8952
    @nisarggogate8952 Před rokem +2

    Awesome explanation!

  • @Ramneet04
    @Ramneet04 Před 6 měsíci

    I tried this with curr and prev approach but got tle then came to this vedio, we actually use this in approach where we sort in other questions i guess. I was really helpful ❤❤

  • @utsavbarnwal7120
    @utsavbarnwal7120 Před 11 měsíci +1

    Such A great Explanation ☺

  • @nagmakhan3165
    @nagmakhan3165 Před rokem

    Phenomenal

  • @Saryupareen
    @Saryupareen Před rokem +1

    what an explaination great!!

  • @Chakss
    @Chakss Před 10 měsíci +1

    Amazing explanation!

  • @anmolraj5054
    @anmolraj5054 Před 6 měsíci

    Bro you r gem

  • @AmandeepSingh-uq3wp
    @AmandeepSingh-uq3wp Před rokem +1

    Great Explanation 👍

  • @umeshbisht1054
    @umeshbisht1054 Před 6 měsíci

    Thanku bhaiya ❤

  • @justgoahead_123
    @justgoahead_123 Před 6 měsíci

    awesome bro !! : )

  • @satyaprakashtiwari5494
    @satyaprakashtiwari5494 Před rokem +1

    Thanks for making this

  • @zaviyakhurshid9097
    @zaviyakhurshid9097 Před rokem +1

    Awesome Explanation

  • @nitinkaplas1532
    @nitinkaplas1532 Před rokem +3

    bhai yrr isse tarah question solve kroge tu 1 saal me subscriber i think 1Million + ho jaege 😄

  • @bhuppidhamii
    @bhuppidhamii Před 6 měsíci

    thank you

  • @satyasanjay1339
    @satyasanjay1339 Před rokem +2

    It did not feel like I was solving a hard problem. your explanation is just awsome.

    • @codestorywithMIK
      @codestorywithMIK  Před rokem

      Thanks a lot ❤️🙏😇

    • @satyasanjay1339
      @satyasanjay1339 Před rokem +1

      @@codestorywithMIK I have a request. can you please make a video on the maximum number of events that can be attended? It is a leetcode medium problem. I couldn't understand its optimal solution.

    • @codestorywithMIK
      @codestorywithMIK  Před rokem +1

      @satyasanjay1339 are you referring to the first part of today’s Leetcode POTD ?

    • @satyasanjay1339
      @satyasanjay1339 Před rokem

      @@codestorywithMIK yes

  • @shivammaurya5464
    @shivammaurya5464 Před 6 měsíci +1

    bahut mast explain kiya hai

  • @ishankiverma9450
    @ishankiverma9450 Před rokem +3

    Very nicely explained..i request you to teach some advanced topics in DSA too!!!

  • @ankushdangi3154
    @ankushdangi3154 Před 9 měsíci +1

    ❤❤

  • @bhartendupant8859
    @bhartendupant8859 Před 6 měsíci

  • @cacklouncle
    @cacklouncle Před rokem +1

    Badhiya

  • @tarunsingh6374
    @tarunsingh6374 Před 6 měsíci +1

    Bhaiya , please try to explain java code also 🤌

  • @piyushsrivastava5883
    @piyushsrivastava5883 Před 6 měsíci +1

    bhaiya simple knapsack approach kyu nhi lagega

  • @vishalplayzz2580
    @vishalplayzz2580 Před 6 měsíci +1

    sorting based on ending time giving us wrong answer ?
    we will be finding nextind from the current index through binary search
    ending time sorting not making sure that it is sorted and starting time sorting making sure it is sorted when finding nxt ind ? is that it ?

  • @satvrii
    @satvrii Před rokem +3

    ❤❤❤❤

  • @deepakarya5310
    @deepakarya5310 Před 6 měsíci

    sir if we change the result value then we are getting overflow exception

  • @vishalplayzz2580
    @vishalplayzz2580 Před rokem +2

    nice

  • @chetanyagupta5801
    @chetanyagupta5801 Před 6 měsíci

    can we also sort based on end time?

  • @chillkro25
    @chillkro25 Před 5 měsíci

    Bhaiya prev name kaa variable bna ke uske basis pr.next job ko take/not take kr lete , ye approach chalega ya nhi , like longest increasing subsequence me prev variable bna ke krte h , pls reply

  • @CodeMode9313
    @CodeMode9313 Před 5 měsíci

    mast maggaan video ::)

  • @user-uh8up3vp6p
    @user-uh8up3vp6p Před 15 dny

    For all those stuck with runtime error-Do not use comparator for sorting use normal sorting that will work fine.

  • @AmarjeetKumar-to9ub
    @AmarjeetKumar-to9ub Před 6 měsíci

    🔥++

  • @soumyasatish7941
    @soumyasatish7941 Před 6 měsíci +2

    Hello! I have been trying to calculate the next index using the stl lower_bound function from index i+1 till end but keep getting syntax errors for
    int next = lower_bound(array.begin() + i + 1, array.end(), array[i][1]) - array.begin();
    I know the problem is with array.begin + i + 1 but don't know what to replace it with. Let me know your thoughts on this.

    • @Raj10185
      @Raj10185 Před 6 měsíci

      yes can be done in this way :-
      class Solution {
      public:
      int dp[50004];
      vector< pair< int,pair > > arr;
      int solve(int i ,vector & starr )
      {

      //base case
      if(i == starr.size())
      return 0;
      if(dp[i]!= -1) return dp[i];

      int nottake = 0 + solve(i+1 ,starr );
      int take = -1e9;

      int nxt_idx = lower_bound(starr.begin(),starr.end(),arr[i].second.first) - starr.begin();

      take = arr[i].second.second + solve(nxt_idx,starr);


      return dp[i] = max(take,nottake);


      }

      int jobScheduling(vector& startTime, vector& endTime, vector& profit) {
      int n = startTime.size();
      // vector dp(n+2,-1);
      memset(dp,-1,sizeof(dp));


      //sort accng to the start time first


      for(int i = 0 ; i < n ; i++)
      {
      arr.push_back({startTime[i], {endTime[i], profit[i]}});
      }


      sort(arr.begin(),arr.end());
      vectornewArrayIndex;
      for(int i=0;i

    • @soumyasatish7941
      @soumyasatish7941 Před 6 měsíci

      @@Raj10185 I want the lower_bound function to search from the index after i till end. Trying to reduce the search space for lower_bound

    • @Raj10185
      @Raj10185 Před 6 měsíci

      @@soumyasatish7941 yes you can do but its already binary search so doesn.t matter much O (logn} is best tc

  • @user-do1eq7tl3e
    @user-do1eq7tl3e Před měsícem

    I am always get confused when to late l

  • @manashchoudhary744
    @manashchoudhary744 Před 5 měsíci

    Which software u r using

  • @sidharthdhiman4522
    @sidharthdhiman4522 Před rokem +1

    sir can you also explain time complexity at the end also for more beeter understanding

  • @sourabhbindal774
    @sourabhbindal774 Před 6 měsíci +2

    Thanks, MIK Sir here is the Bottom-up solution derived from memoization-
    class Solution {
    public:
    int getIndex(vector& arr, int val, int l, int r) {
    int res = r + 2;
    while (l

    • @codestorywithMIK
      @codestorywithMIK  Před 6 měsíci +1

      I feel so happy and proud that we are now able to derive bottom also.
      Thanks a lot for sharing 😇🙏❤️

  • @bhuppidhamii
    @bhuppidhamii Před 6 měsíci

    classic dp

  • @abc-ym4zs
    @abc-ym4zs Před rokem +1

    sir can u i dont know how to write comp function generally we will write as bool comp(auto v1,auto v2)
    {
    return v1[0]

    • @codestorywithMIK
      @codestorywithMIK  Před rokem

      Hi there,
      I have started a playlist where I will be teaching comparators, STLs etc. - czcams.com/play/PLpIkg8OmuX-KtmrBzx-dAzRDp0xn_Xjls.html
      Also, you can see this resource that I have created on Github - github.com/MAZHARMIK/Cpp-STL-Quick-Help

  • @roshangeorge97
    @roshangeorge97 Před 8 měsíci

    can we use greedy?

    • @souravjoshi2293
      @souravjoshi2293 Před 6 měsíci +1

      Let's consider an example to illustrate why a greedy approach may fail for this problem :
      Consider the following jobs:
      Job: A B C
      Start: 1 2 3
      End: 3 5 6
      Profit:10 5 8
      If we sort the jobs by their end times in ascending order, we get:
      Job: A B C
      Start: 1 2 3
      End: 3 5 6
      Profit:10 5 8
      A greedy approach might consider selecting jobs based on the highest profit at each step. If we follow this greedy strategy, we might select Job A and Job C, as they have the highest profits.
      However, the optimal solution is to select Job B and Job C, which results in a total profit of 13. The greedy approach would lead to a suboptimal solution in this case.

  • @shivkumar-og4ow
    @shivkumar-og4ow Před rokem +1

    bhaiya leetcode contest solution bhi upload kro

  • @tanishchordia4813
    @tanishchordia4813 Před 3 měsíci

    Hello mik , today I tried the exact solution which you taught in the above video but the last testcase gave runtime error. I thought maybe i missed somthing so just copy pasted your solution and your soltuion also gave the runtime error on the last testcase can you help me?

    • @user-uh8up3vp6p
      @user-uh8up3vp6p Před 15 dny

      don't use comparator fubnction for sorting use normal sorting

  • @keertilata20
    @keertilata20 Před 11 měsíci +2

    hehe i am so happy i did on my own....
    int solve(vector &arr, int ind, vector &dp){
    int n=arr.size();
    if(ind >= n){
    return 0;
    }
    if(dp[ind] != -1){
    return dp[ind];
    }

    int nxtInd = lower_bound(arr.begin(), arr.end(), vector{arr[ind][1], 0, 0}) - arr.begin();
    int take = arr[ind][2] + solve(arr,nxtInd,dp);
    int notTake = 0 + solve(arr,ind+1,dp);
    return dp[ind] = max(take,notTake);
    }

    int jobScheduling(vector& startTime, vector& endTime, vector& profit) {
    int n=startTime.size();
    vector arr(n, vector(3, 0)); //{s, e, p}
    for(int i = 0; i

  • @gauravbanerjee2898
    @gauravbanerjee2898 Před 6 měsíci +2

    Thanks for the explanation Bhaiya but why did you took result as n+1 ??

    • @codestorywithMIK
      @codestorywithMIK  Před 6 měsíci +3

      Good qn.
      Actually if you notice, whatever index you return from getNextIndex function ,you pass that index in recursion call i.e.
      int next = getNextIndex(array, i+1, array[i][1]);
      int taken = array[i][2] + solve(array, next);
      So, if you get no valid element from getNextIndex , I am returning n+1, because when I will call
      int taken = array[i][2] + solve(array, next); (with next = n+1), I will return from the base case
      if(i >= n)
      return 0;
      You can return any invalid value from getNextIndex in case you don't find any valid element BUT, make sure you handle it in base case.

    • @gauravbanerjee2898
      @gauravbanerjee2898 Před 6 měsíci

      @@codestorywithMIK Got it thanks a lot for the clarification bhaiya ❤

  • @VinayKumar-rq5kd
    @VinayKumar-rq5kd Před 6 měsíci +1

    why did you initiliaze n +1 to result. is it n.

    • @codestorywithMIK
      @codestorywithMIK  Před 6 měsíci +1

      Good qn.
      Actually if you notice, whatever index you return from getNextIndex function ,you pass that index in recursion call i.e.
      int next = getNextIndex(array, i+1, array[i][1]);
      int taken = array[i][2] + solve(array, next);
      So, if you get no valid element from getNextIndex , I am returning n+1, because when I will call
      int taken = array[i][2] + solve(array, next); (with next = n+1), I will return from the base case
      if(i >= n)
      return 0;
      You can return any invalid value from getNextIndex in case you don't find any valid element BUT, make sure you handle it in base case.

  • @035-harshitsingh7
    @035-harshitsingh7 Před rokem +1

    bhaiya aap bottom up approach se kyun nhi btate-- tabular wala form

    • @codestorywithMIK
      @codestorywithMIK  Před rokem +2

      Hi Harshit,
      Actually i will cover all ways to solve DP in my DP concepts and Qns playlist - czcams.com/play/PLpIkg8OmuX-JhFpkhgrAwZRtukO0SkwAt.html

  • @harshtiwari416
    @harshtiwari416 Před 6 měsíci

    Bottom Up video????

  • @shashanksaurabh6478
    @shashanksaurabh6478 Před měsícem

    Isn't it a greedy?

  • @abhishekverma7604
    @abhishekverma7604 Před 10 měsíci

    bhya mujhe isme fractional knapsack ki vibe aa rhi hai...😂

  • @MakeuPerfect
    @MakeuPerfect Před rokem +1

    bhaiya wo duplicate wala akbar samjhate kya hua bsearch mein

    • @codestorywithMIK
      @codestorywithMIK  Před rokem +3

      Take this example :
      {start, end, profit}
      { {1, 3, 50}, {2, 4, 10}, {3, 5, 40}, {3, 6, 70} }
      Suppose you chose to do job 1 - > {1, 3, 50},
      Now, you need choose next job whose starting point is >= to ending point of your 1st job {1, 3, 50}
      So, you have two options {3, 5, 40}, {3, 6, 70}
      Using binary search, the mid might point to {3, 6, 70}, but you need to find the first job which has starting point >= your 1st job end point. That's why if my mid points to {3, 6, 70}, I still try to go left (r = mid-1) and see if we can get more task to left which has starting point >= end point of 1st job
      Hope this helps

    • @souravjoshi2293
      @souravjoshi2293 Před rokem +1

      @@codestorywithMIK Yeah correct.
      Since we want to try all possibilities, we don't want to miss {3, 5, 40}
      and would try with it and then later try with {3, 6, 70}. Right ?

    • @souravjoshi2293
      @souravjoshi2293 Před rokem +1

      Or I think we should try to do the dry run for this example , it will help :
      [6,15,7,11,1,3,16,2]
      [19,18,19,16,10,8,19,8]
      [2,9,1,19,5,7,3,19]

    • @debanga3501
      @debanga3501 Před rokem +1

      @@codestorywithMIK Ek no explanation

    • @MakeuPerfect
      @MakeuPerfect Před rokem

      @@codestorywithMIK at first mid is pointing to 3/2=1 index then we find the mid is mid+1 to till the end and mid pointing to 5/2=2index,
      So mid point to {3,5,40}.

  • @user-le6ts6ci7h
    @user-le6ts6ci7h Před 6 měsíci

    Hey MIk I have been looking for jobs , will you mind giving me a referral at your company.

    • @codestorywithMIK
      @codestorywithMIK  Před 6 měsíci

      Hi there,
      Unfortunately my company has announced Hiring freeze due to bad market condition.
      But feel free to share your resume with me on my email id (you can find email from my github profile), I will try my best to share it with my friends and colleagues to check.

  • @ishabharwal1699
    @ishabharwal1699 Před 6 měsíci +1

    hi can you please tell me whats wrong in my solution?? take condition
    class Solution {
    public:
    int recur(int idx,int last,vector& st, vector& et, vector& profit){
    if(idx==profit.size()){return 0;}
    int take=0;
    if(last

  • @VedBrahmbhattBEE
    @VedBrahmbhattBEE Před 6 měsíci

    Can Someone tell me why my code is giving overflow runtime error ?
    class Solution {
    public:
    int n, dp[50001];

    int getnext(vector& arr, int l, int currentjobend) {
    int r = n - 1;
    int ans = n + 1;
    while (l = currentjobend) {
    ans = mid;
    r = mid - 1;
    } else {
    l = mid + 1;
    }
    }
    return ans;
    }
    int solve(vector& arr, int i) {
    if (i >= n) return 0;
    if (dp[i] != -1) return dp[i];
    int nextjob = getnext(arr, i + 1, arr[i][1]);
    int take = arr[i][2] + solve(arr, nextjob);
    int nottake = solve(arr, i + 1);
    return dp[i] = max(take, nottake);
    }
    int jobScheduling(vector& startTime, vector& endTime, vector& profit) {
    n = startTime.size();
    memset(dp, -1, sizeof(dp));
    vector arr(n, vector(3, 0));
    for (int i = 0; i < n; i++) {
    arr[i][0] = startTime[i];
    arr[i][1] = endTime[i];
    arr[i][2] = profit[i];
    }
    auto comp = [&](auto& vec1, auto& vec2) { // to sort array based on the starting element
    return vec1[0]

  • @ChiragWadwa
    @ChiragWadwa Před 6 měsíci

    pls help me find the start mistake , isme maine lower bound use kia , galat kyu aa rha h , pls help!!!
    class Solution {
    public:
    int getNext(int start,int target,vector &arr){
    auto it = lower_bound(arr[0].begin()+start,arr[0].end(),target);
    int ind = it - arr[0].begin();
    return ind;

    }
    int solve(int curr,vector &arr,vector &dp){
    if(curr >= arr.size()) return 0;
    if(dp[curr] != -1) return dp[curr];
    //take
    int nxt = getNext(curr+1,arr[curr][1],arr);
    int take = arr[curr][2] + solve(nxt,arr,dp);
    //notTake
    int notTake = solve(curr+1,arr,dp);
    return dp[curr] = max(take,notTake);
    }
    int jobScheduling(vector& startTime, vector& endTime, vector& profit) {
    int n = startTime.size();
    vectorarr(n,vector(3));
    for(int i=0 ; i

    • @wearevacationuncoverers
      @wearevacationuncoverers Před 6 měsíci +2

      If you want to use lower_bound to find the first job whose starting point is greater than or equal to currentJobEnd, the condition should be vec[0] < currentJobEnd in the lambda function of lower_bound
      Something like this :
      int getNextIndex(vector& array, int l, int currentJobEnd) {
      auto it = lower_bound(array.begin() + l, array.end(), currentJobEnd,
      [](const vector& vec, int val) {
      return vec[0] < val;
      });
      return it - array.begin();
      }
      This will work.

    • @ChiragWadwa
      @ChiragWadwa Před 6 měsíci +1

      @@wearevacationuncoverers thanks a ton bhay ...but can u tell why my code was failing???

    • @ChiragWadwa
      @ChiragWadwa Před 6 měsíci

      @@wearevacationuncoverers and also can u tell how u exactly wrote this compator thing??? , ive seen miks video of compaator , but still i am not able to get ,, cn u help me out pls?

  • @pavankumareluri9226
    @pavankumareluri9226 Před rokem +1

    nice