Transcript
Use with ChatGPT / Claude Auto-scroll A
foreign
right so uh today is going to be our first I believe of two problem sessions covering dynamic programming um I find dynamic programming is one of these interesting parts of an algorithms class where like somehow the people thatare really good at it are completely disjoint with the people that are good at all the other parts of the algorithms class so for some of you guys that might be promising uh and for others maybe a littlebit less so uh so maybe we'll spend just a minute or two kind of reviewing the basic ideas we're going to apply uh in these problems because they'll follow more or less the same template although of course asusual in 6006 if you like to put some interesting window dressing around it so that it's not totally obvious what you're doing uh uh and then we'll do a bunch of sample problems um right so let's let's talk
a little bit about dynamic programming and the basic uh idea here so dynamic programming is kind of a funny outlier in 6006 in that like for example in the data structure is part of the course we learned likewhat you know struggling to think of a data structure like like a useful you know like trees and arrays and whatever these are actually things that you can code like if you look in C plus plus like there'sa there are well plausibly it could be an implementation of a tree in there some way um and so these are like useful algorithms that you could maybe even read the pseudo code and there's a universe where youreally do translate that pseudocode into something inside of your laptop dynamic programming is a little bit less so this is more like a meta I don't know if you call it a meta algorithm or a problem-solving approach or
what um but it's not like you somehow say I'm going to apply the dynamic programming algorithm to this problem but rather it's sort of this big class of things that all follow a similar template or or sort ofapproach to thinking about problem solving which I think sort of explains why actually in some sense the last couple lectures that you've seen and I guess if I'm getting the the time sequence of our course right the nextcouple ones that you will see um and the problem sessions actually start to coincide in the sense that like when Eric was teaching your diet's dynamic programming how did he do it well he didn't like write down wellhe sort of wrote down some template for dynamic programming but then we just did a bunch of sample problems and that's exactly what we're going to do today uh so somehow all of these things are just going to
converge uh in in this part of our course uh because dynamic programming it's really more of a way of life uh than any particular algorithm uh and this is a pattern that I think you see a lot inadvanced algorithms like for example in my universe numerical analysis like when you talk about the ADM algorithm it's actually totally useless algorithm what matters is applying it to a particular problem uh and and this is a sort ofI think a more mature or grown-up way to think about a lot of things in algorithms right that pretty soon this sort of general purpose stuff that's useful all the time I think I think it starts to dispersea little bit in favor of different patterns and mechanisms that you're used to thinking about so there's my 10 seconds sort of philosophical introduction know what we're doing during which I've managed to chase this table across the room
you know I played I did College on the west coast and I thought I was going to be a music Major and there's a Piano Master Class where we forgot to put the little Clips on the wheels andour there was an earthquake and I just thought I was really nervous because the piano was literally slipping away from me uh and I can never think of that that Chopin Nocturne quite the same way um but inany event uh in dynamic programming uh Eric laid out for you guys a particular sort of set of steps uh that are sort of a useful problem-solving approach in the dynamic programming Universe in today's film session I'm goingto try and help you guys translate a little bit from this template to what it means to actually write code to implement a dynamic programming algorithm because I think it's a little easy to forget that here but uh
on the other hand on your homework when you're writing out answers to algorithms problems is perfectly fine to follow this template even letter I guess literally letter for letter uh and answer each of these questions and then sortof the remaining glue that you need to actually write the code is not terribly uh exciting from an algorithm's Theory perspective um so the basic idea here is the there's a lot of different problems that can be writtenrecursively in some sense uh certainly we we've encountered many of those in this course in fact I think the bias in the way that we've presented algorithms that don't have to be recursive is to write them in arecursive way um and and the point here is that when you have a recursive call and you repeat something you know you you give the function the same input more than one time you might as well remember what
you got the last time you saw that input and then you don't have to do that computation again really in one sentence I think that's roughly the logic behind all these dynamic programming things yeah so there's no reasonto be too redundant with lecture uh for just sort of the 10 second overview I think that there's an example which is simultaneously good and misleading which is this Fibonacci Sequence uh it's good in the sense that thelogic of dynamic programming is really easy it's bad in that the run time is kind of weird to think about um but remember those your Fibonacci Sequence looks something like f of k equals F of K minus 1plus F of K minus two and if you look uh your sort of recursive call tree here right like let's say that I do k equals four right then it's going to call you know my function f is
going to have to evaluate it at 3 and 2 and then the 3 is going to evaluate at 2 and 1 and so on and the thing to notice is that when I call F of 4 or ratherF of 3 here if there were three somewhere else in my tree I get the same number right so in particular F of 2 and F of 2 both of these are going to take some amount of algorithmicwork but if just the first time I see a 2 I have a little piece of scratch paper and I say ah anytime I see uh k equals 2 just return this number rather than doing recursive calls thenin fact if there's any subtree underneath this thing uh I I've just pruned it from my tree right and and and so that's the basic logic here uh and that's basically this the the Paradigm that's going on in
this this sort bot uh acronym uh which is is uh you you first take your problem and divide it into sub problems that is mysterious why is this board moving um oh there's a phone in my pocket Ibumped against the wall uh
foreign
right uh yeah so the first thing I want to do is to write my my problem as sort of this sort of form notice that we've done this a lot in this class we've written things recursively the differencehere is the the sort of argument that goes into recursion is typically maybe a little simpler than you know like putting some giant data structure inside of there or something like that right so for instance merged sort youcould write in this Paradigm I guess we covered that but it's probably not the most natural way to think about merge sort then we need to relate our sub problems to each other so for instance in the Fibonaccisequence problem I just gave you the relation that sort of what defines the problem incidentally this is what a model for the reproduction of rabbits I think if I remember reading the history of the Fibonacci sequence um and
then I think to me the most not necessarily unnatural but I think the thing that maybe is hardest to translate to an algorithm if you're thinking about writing code is this like oh man this is going to bea problem uh this idea of topological uh order the basic idea here is that like if F of one depended on F of F 2 and F of 2 dependent on of 1 I'd be in a lot oftrouble right because somehow my tree would never converge from one thing if I made these recursive calls and I'd never be able to memoize or kind of remember a value uh when I move on right and so theidea here is that there's some ordering of my sub problem so that I can build up a solution and there's sort of two dual ways to think about why that's useful so in the memoization universe right what do
I do I just add an if statement saying you know if I've already evaluated F okay return it that's perfectly fine the other thing I can do is if I write my sub problems in topological order then Ican sort of go in the reverse Direction and build up my memoization table so for instance uh for uh the Fibonacci sequence problem I could do F of one and then F of two and then F of threeand F of four all the way until I get to the K value that I actually wanted and those are just Duels of the the same coin they're exactly the same approach of the memoization version sometimes you canprune out some problems that you didn't actually need to solve so for instance maybe this was F of K minus seven and so I can like skip a few indices in my array I don't think typically that has
a big effect on runtime for the problems that we've seen but it could um plausibly uh in some Universal I'd have to think about a problem where that that makes a difference um right and then I think thebot part of swordpod is a little easier to think about uh you have to make sure that this recursion has you know a base case like when is this thing going to stop that's exactly the same it's justany recursive algorithm um the O for original I think is a little bit retro retrofit to to make short but sound nice but I think the idea here is that you need to go back to original problem andmake sure that it corresponds to one of the function calls that you've written and all those complicated stuff hopefully that's a reasonable characterization and then finally the t is more you know these are for describing your algorithm the
last ones for analyzing it um and again the the bot part of sortbot almost applies to anything we've done in 6006 like you should always analyze your runtime um okay so in any event that's my 10 minute versionof uh the last couple lectures uh and I think more or less enough to get us started with some sample problems here sorry I couldn't help it I like to teach things okay so uh right so in ourproblem session we have a few of the homework problems from last year uh to go over um if it makes you guys feel any better I got myself all balled up on one of them last night while IWas preparing for today and I I look forward to doing that in front of all of you guys now uh right so I'm go afraid of this so I'm going to to the next port um okay so in
our first problem uh Sunny studies this was somehow you know the like cute naming conventions we have in 6006 got really meta in this problem because there's a problem about Tim the beaver uh but as we all knowuh Tim is MIT backwards so like he happens to fit into this goofy game that Jason likes to play in in writing homework problems anyway um but it's also the MIT mascot anyways I got very excited um rightso so what's going on in this problem so Tim the beaver has kind of an interesting uh you know mathematics I think you would call this a Martingale as you flip the coin a little bit when he sawthis problem but uh luckily Tim the beaver is a deterministic uh kind of a guy uh and he looks at the weather outside and if it's a temperature tee apparently Tim the beaver is okay with with boiling um
the higher the temperature uh the happier Tim gets so this is the first derivative kind of a phenomenon in particular uh on a on a given day if I have a temperature t uh Tim the beaver has twothings that he can do to change his mood apparently Tim the beaver's mood never stays fixed it always goes up and down um in particular you can either uh go outside
in which case the happiness increases by T
okay or he can stay inside
in which case his happiness decreases
by T okay so every day Tim the beaver uh he wakes up he he I really want to say that he checks for his shadow but that's that's a gopher right um in any event he wakes up inthe morning he checks the weather uh and he makes a determination does he want to go outside or not and if he goes outside he gets happier by an amount that's equal to the temperature if he stays insidehe gets less Happy by an amount that's equal to the temperature by the way I think our solution is perfectly fine if temperatures are negative here in which case I guess everything would kind of flip uh intuitively butthere's no reason to get too hung up on that but of course there's a Twist here um so Tim as with many of you has end days until his final exam
and he's worried about studying yeah so uh in particular um he never wants to go he's you know he's come up with a personal resolve to never go outside more than two days in a row yeah um soright um
and so the question is right because that way you know he has to stay inside and study at least one out of every three-ish days okay so the question is how can Tim maximize his uh his happiness incidentallythat's you know machine learning sometimes they call that minimizing regret which I always found to be like a very sad way to think about algorithms when there's a totally dual version but but Tim's an optimistic guy he wantsto maximize his happiness subject to this constraint the he cannot go outside more than two days in a row right so like if I go out on Monday and Tuesday I have to stay inside on Wednesday yes Ithink there's no effect to his happiness when he stays in there's no effect to his happiness when he stays in
uh no it says with a decrease in happiness when T oh when T is negative that's not actually going to affect our problem at all
sure yeah I can fix this life uh and this is what happens when I do the problem myself before looking at the answer and then don't check it closely um fine so uh let's let's change that I likethis problem better uh somehow psychologically but that's okay um right so uh Jason correctly points out that if you actually read the problem uh what's what's uh asked there is is slightly different that when he goes outside hishappiness increases by T if he stays inside his happiness does nothing right so um it stays the same my apologies so um Tim the beaver is a particularly optimistic fever his happiness can only increase in time assuming helives in a climate with positive temperatures okay now I think I've got it right now cool let's see if I can still do this yeah I think basically nothing changes okay that's great all right we're gonna do it
umokay so right so the question is how do we uh solve this problem uh and and thankfully I think we put the easiest problem first uh and in particular if we're we're following our ballot Paradigm here um somehowthere's there's a set of sub problems that are staring Us in the in the in the face that's the word I'm looking for uh in particular uh well there's sort of only one index in our problem which iswhat day it is so the obvious thing to do would be to say can we figure out the maximum amount of happiness for days say I to the last day by the way if I do that I'm usingthe prefix version of my problem uh ah suffix version of my problem I could also do it the opposite way and work from the end back in um maybe at if we have time all the way the end
we'll do the second one but it doesn't doesn't really matter okay so in particular um just to add a little bit of notation let's say that uh T of I is equal to the temperature on day I okayand now we're going to make a new thing which is going to be the actual variable we be want to compute this is going to X of I which we'll write is the maximum happiness
that you can achieve if you only consider the calendar from day I to day n I guess inclusive okay uh incidentally just for convenience we'll assume that x i is equal to zero if I go past the endof my array which I think is kind of a typical thing to do in these DP algorithms okay so the question is can we actually come up with a recursive algorithm that computes X I uh using this niceuh sort of topologically acyclic uh way of of thinking about our problem the answer is obviously yes or I wouldn't be here today um and and so you know in the absence of a smarter idea let's let's justdo the the Toucan Sam approach here and follow our nose and see if we can just write our problem in terms of other ones so in general let's say the the Tim the beaver wakes up on day I
he has basically two decisions that he can make right he can either stay inside or he can not stay inside he can go outside uh right so so let's let's just basically uh handle these three cases so incase one um he stays insidewell now what happens to his happiness well according to my revised version of this problem nothing right so uh in particular um what do we know well if he stays inside then he has any decision he can maketomorrow it doesn't matter he can go inside and go outside whatever because by having stayed inside he's earned himself two free days of going outside if he wants right so in particular in this case we can convince ourselvesthatthis is true in our uh I think yes um right so in other words uh well he gets no utility for today he wakes up tomorrow and he can make whatever decision he wants okay the second thing he
can do is go out
this is where things get a little tricky right can I just do like you know take TI and add it to x i plus one what goes wrong
maybe you go three days in a row right you you somehow have to remember that right uh and and so that's where things are a little bit of a headache um the in particular if I go out todayand tomorrow I can't go out the day after that um and somehow if we just uh dealt with this one case as t i plus x i plus one we wouldn't remember that right and that's a problem soinstead what we can do is think of there being two sub cases right so what we're going to assume is that not only does he go out today but he's free to go out tomorrow and we're going tokind of make that recursive assumption as we we move down on our way uh so if we do that uh well now we have case a and case b so in case a he goes out today and he
stays in tomorrow
yeah okay so what happens in this case wellby the way I'm using this kind of weird arrow notation I don't know if this is good or not but essentially the point is that I'm keeping track of cases and then eventually going to want to have totake the max over all of these things so I don't like the equal sign because somehow that's a little misleading um right so in that case well he gets the utility of having gone out today tomorrow he staysin which means that the day after tomorrow he can do whatever the heck he wants right he has he has free ring so I can write that using this recursive call okay uh similarly
uh right so
I'm getting the hang of this sorry this is way too entertaining for me I can play with this board all day um okay so in in case 2B he goes out today and he goes out tomorrow
Okay so he's a party animal he is an animal and he's going out a lot um right so in that case what happens well he gets that he gets uh today's utility he gets tomorrow's utility uh the dayafter he has to stay in so we might as well skip it and then he can do whatever he wants the day after that okay so we if go back I guess technically we should revise our definition ofx a tiny bit that it's not the maximum happiness well we can convince ourselves that it's the same thing but really it's not the maximum in the happiness for day I through n it's the maximum happiness for dayI through n under the assumption that he has permission to go out on day I right and that's really what's going on in our our recursive set of calls here okay so does our recursion uh make sense here
cool all right so uh let's see here so if we're following our sort but I keep reviewing papers that use the word Paradigm a lot so I feel I feel like I should do that so what is Tis the topological order notice uh that um right x i only depends on larger eyes so in terms of our topological order the dependence graph is really simple right it's just a line um so remember that you canthink about topological order or you can think about being a cyclic graph those are equivalent we covered that in this course I kind of like thinking about acyclic graphs um right so X1 depends on x2 depends on X3it depends on X4 that graph has no Cycles so we're good um wait what's our so next we have to come up with our base case for our recursion notice the the way I have chosen to solve this
problem is uh by calling future indices which means that my base case says at the end of my array right because that's sort of like the lowest down in the recursion train uh recursion chain is what it's goingfor but I kind of like the recursion train better um in particular on day n well if he has permission to go out on day and um he can do one of two things he can either go outor not it doesn't matter right so in particular we can say that that's the max of 0 or t of n remember I didn't tell you that temperatures have to be positive yeah maybe he's uh he's a Celsiuskind of a beaver okay right uh uh and and then in addition to that um for convenience notice that like there's a universe where I look beyond the end of my array in my recursive call here um so
I should probably think about a few extra X's uh obviously the utility of going out on a day that doesn't exist is zero uh so we can say that x n plus one equals x n plus two equalszero okay I've managed to use way too much space for one simple algorithm problem
okay so
yeahokay good credit for that okay um right so now uh we need to do the O and the t uh so what's our original problem well remember that he wants to maximize his happiness starting on day one umso our original problem is just X of one um or is it so remember that Tim the beaver this is you know your instructor is very sloppy when it comes to actually reading the problems as you saw atthe beginning um a second mistake for which I would have personally lost points where I to solve this problem on my homework is that it didn't ask for just the maximum amount of happiness that Tim could achieve that'snot very practical for your everyday Beaver uh but rather um he wants to know the actual plan he wants to know what days he can go out and what days he can't yeah and I haven't actually told you
how to do that right I've only told you how to compute X which is just the maximum amount of happiness if I were you guys I I think this is a perfectly reasonable simplification that's like a warm-up problemto solve in fact I would argue it's less of a warm up and more the Crux of the problem uh and then going back and making sure you can convince yourself that you could actually reconstruct the solution ummy way of solving this was ever so slightly different from the one in the problem but they're equivalent um which is to say I can make a second array I won't write it down because I'm slow ready thatjust says on every day whether I took option one option 2A or option 2B right and now I can reconstruct my plan very easily right so I look at X1 if I took option one uh then I stay
in and I look at you know day two if I took option 2A then I can label today tomorrow and the day after oh wait uh yeah that's right I can label today's Choice tomorrow's Choice the day isafter Choice and then look three days later uh and we're Chris that way um or option b is is kind of similar right so a reasonable way to reconstruct the actual set of what days you go out andwhat days you go and is this to remember as you do your your memorization or or whatever uh whether you did option one two a or 2B and then it's pretty easy to reconstruct from there maybe I'll letyou guys convince yourselves of that at home or in the last eight seconds if you happen to be the two audience members that I have uh and then finally um right we need to do our time thing and
most of the time arguments here follow more or less the same pattern which is you count the number of sub problems and the time per sub problem you multiply those two things together uh and you get your runtime we're going to see in one problem on this problem set that's not quite right because we have to account for some pre-computation but uh in this case it is right so right so let's see what are oursub problems here well essentially I guess I didn't actually say it but you have to take the max of these three values um this is the max of three Expressions which have a constant number of plus signs andlookups in memory and all that good stuff so each subproblemtakes order one time how many sub problems are there well there's I guess n plus two uh max if you want to be conservative about it uh so in particular there's order N Sub problems right so all I
have to do is multiply these two things together and my algorithm takes order and timeand that's our solution to problem number one any questions so far yes uh-oh when I was thinking of problems before him I was wondering could you use base cases right now we have two different kinds of base casea base case for x for things after
10 plus 3 equals zero as well what would that do could I remove the first one and add an X of n plus three yeah I guess that's fine I'm sorry that's not a particularly helpful answer for thepeople watching on video my answer to this question you can't hear is yes um right so uh the question to uh repeat uh was you know this base case is somehow kind of complicated looking to be fair it'sthe one that I was giving him assignment but that's okay um but the the question is is this truly necessary in particular can I get rid of the xn case and instead add a third day past the endof time uh which also has value zero and if you kind of look at that plus case b I think you uh or rather case a I think you're convinced well case A and B for that matter you
can convince yourself that these are equivalent right um that's absolutely right so so I could add a third day after the end of this thing which also has value zero or by the way I could just say inmy code if n is Big you know if I is bigger than n returns zero that's the same thing um yeah and then I guess I don't have to worry about that xn case yeah these are the sameyou know he eats their own fabulous question any any others uh that I can answer while we're at it cool all right so that's problem oneright I don't like this big Chuck you know okay so problem two is the one that got me all hot and bothered yesterday so let's see if we do any better uh in front of people because that's usuallythe best way to improve uh problem solving skill uh right uh so in problem two which annoyingly is also probably the most practical uh problem on on this problem so essentially you have a uh I suppose I should
write some stuff down right so in problem Oh I used the wrong side two uh you have an operating system men X whatever uh which is a uh you know apparently it's a very simple oh I get itdoesn't mean I have to like it um right so in me mix um no yeah uh apparently the only thing that my operating system can do is uh compute edit distance between files and it wants to do soefficiently so we have that a file is a sequence of strings
and I believe we say their length is less than or equal to K that's going to come into play a little bit later and the strings are basically just lines of the uh the different files so there's threedifferent ways that we can change a file um so here are the changes we could dochange number one is to add a line change number two is to remove a lineand change number three is to swap but a caveat for this interesting this model of of of what's cheap and what's not is that apparently swapping two lines is cheap because they exist in memory like maybe I'm Idon't know using like a linked list or something to store files and so swapping two pointers isn't so bad uh but inserting and removing a line is hard because I don't know memory allocation is expensive like you know
Minix is actually operating on clay tablets and you know I can top my clay tablets into different slices and just pick them up and swap them and that's fine but you know if I want to add a lineto my file I have to go to the Tigris and Euphrates and pull out the or whatever it was the eugris and the typhraties and and pull out a you know Stone it's a lot of work to makea new line or to dispose um right so these are expensiveand this is cheap right and so the question uh that I'm trying to say uh that I'm trying to say and that the problem is trying to ask uh is that you are given files A and B umwith n lines each
uh you want to know what the uh the minimum number of non-swap operations it'll take and so in other words the minimum number of times you need to add and remove lines to transform a into B right um
uh essentially with low costand in fact just to be nice I think that's actually kind of a critical hint in this problem we give you the runtime um and I'm going to kind of ignore it in my answer notice that I didsomething wrong and then go back and fix it this is different from the way the answer is written where you know God came in and said like oh we observe that we're probably going to need this thing sowe're going to go ahead and do it here I think that's that's maybe not representative of the logic here so um right so the the runtime here is K and plus N squared the first thing to notice there'sa K here yeah and and so someday we're gonna have to compare our strings right like because that's what K is and I think that's sort of sort of the hint that's implicit in this problem it's easy to
miss uh and and and so indeed what notice we're going to is we're going to look at our solution and say well wait a second if we didn't incur a factor of K we must have done something wrongum and and indeed that's that's going to be the case but uh it's only a minor uh fixed to change it oh I'm sorry yeah and and um right when I swap things uh they have to be adjacentI can't write at the bottom of the board um that's adj supposed to be for those watching at home uh but they have to you can only swap lines that are adjacent um as they appear in their originalfile I'll say it out loud rather than try and write take it because it's going to like the rest of the lecture to do that any other things I've threatened this High likelihood I'm bad at this okay so
uh this it's one was annoying and and and not actually annoying it's actually a relatively easy instance of a very well-known Dynamic program plus a tiny bit of additional stuff which is called edit distance um in fact Ithink if you guys are looking for intuition on this problem you might Google that one first um as sort of a Rosa oh in fact you're doing a recitation oh that's why it's it's not totally unreasonable to comeup with the answer here even better um but even if you hadn't you know this is just another dynamic programming uh problem that's just like a little bit more annoying than your than your average uh dynamic programming problemuh now the solution written out in the course nodes works from sort of the last line of the file downward in some sense a up upward whatever um I like literally lost two hours of my life trying to
think about editing files from the end up and just getting myself all upset and confused so so here I'm going to attempt to do it in the other direction and probably introduce a bunch of mistakes in the processso what do we do in dynamic programming if we don't know what else to do we we do sort sort stuff sort bot uh and so let's do that here uh so in particular what are our sub problemsthis is a little bit funky it's actually even before we do the S of sort pack let's think about our problem a little bit um let's think about like what it actually means to edit a file because thisis what helped me sort of think about the right right answer here which is to say you know so so what's going on I have like two documents you know this is document a this is document B right
each one of them is composed of a bunch of lines and I'm basically trying to turn a into B and the only thing I can do is like Scribble out a line insert you know just hit the enterkey or do a third thing where I kind of like swap to uh things that are adjacent to one another this is the only thing I can do and the way that I like to think about this problemthere's kind of an annoyance here which I think is a typical annoyance in dynamic programming problems which is that the order of operations suggests that this problem is a lot combinatorially more difficult than it is right because likeokay let's think about how I actually edit documents like I spend two-thirds of my day editing bad grad student writing is like you know I'm like jumping all over the place between different lines like first I delete this
line and then maybe I go to the bottom of my document delete some other one that would be a big problem from a dynamic programming perspective I can't jump all over my document because keeping track of that wholeedit history is going to be somehow combinatorially ginormous right I'm not you know the track changes button in Microsoft Word I want the minimum number of changes and if I have to recurse over like all possible edits toevery single line in any order that's an awful lot of like factorials and Two To The Ends floating around that that I don't want to have right and and so that's the sort of Crux of of the challengehere uh is to organize my approach to editing these files in a way that doesn't require me to have to to do this sort of combinatorial jumping all over the place and I think it's also the one where
the sort of like I know Jerry Kane at Stanford talks a lot about the the recursive leap of faith you know like somehow dividing your problem into organized sub problems that's that's really where the the challenge uh liveshere so if I were a more organized PhD advisor the way that I would edit a file um or a clay tablet uh I guess in this case um would be linearly right that like I might as welldo whatever the heck I'm going to do to line one before I move on to line two right and like at the end of the day like even if I did stuff in a different order you could convinceyourself that I could always order it in such a way that like all the edits that I do to the first line kind of happen before lines later in the document uh with the possible exception of this swap
thing um but we'll see that that somehow doesn't matter and and moreover if I do an edit I might as well do the edit to make things better right like there's no reason to just start like willy-nilly insertingand removing lines um I might as well always do an operation that improves stuff and so thinking about that sort of logic leads me to the to a particular way that I might write down my S my subproblems here which is to say that I'm going to think about editing my document line by line so in other words like once I've dealt with line one meaning that I've found some way to mess with it andmake it match line one of the other guy I'm just gonna kind of think about removing it and then thinking about the rest of the document instead of saying aha that's then it sounds like recursion and that's right
that's how we're going to solve this problem okay so in particular here's going to be our our thing I'm going to do a slightly different one in the solution so you guys should all be vigilant which is I'mgoing to write x i j to uh B the min work to convert
I'm not a python programmer but hopefully I got this right um I colon is going to be everything from I to the end of the file right so in other words this is the suffix version of our problemum and uh the uh into B J colon like that okay um so in other words like I have like a little it's kind of like a video you know like I think about Tetris you know once onceyou get that full line of blocks you can just throw that line of blocks away and the whole video game moves down there's somehow something very similar going on here which is the second I've managed to get amatch for line one of document into line one of the next document I'm just gonna like throw it away and pretend like I have two documents with one less line in them now the thing that got me all
hung up last night my original problem assumes that both of my documents have the same length but here I'm not making that assumption right and essentially what we're going to figure out is if that actually doesn't matter awhole lot that if I end up with one document of length K and well I shouldn't use K one document of length L and another document of like zero what's the amount of work that I should do toconvert well L right because my only choice is to insert a bunch of lines in one document by the way or delete a bunch of lines from the other those are dual to one another exactly the same I'mphilosophizing a lot because I'm also convincing myself that my answer is okay in the process okay uh right so this is going to be our set of sub problems and now we have to do um the uh the
r right we have to relate something we struggle with in the math department sometimes um uh and essentially uh the way that I went about this uh is to just do a billion different cases of all the possibleedits that I could do to line I and line J and that's perfectly fine in this problem I think the problem is a little slick and the way that they've written the solution they've convinced themselves that like somethings are equivalent to others and removed them but you didn't have to as long as there's a constant number of cases you're you're golden Ponyboy uh so in particular uh let's think about some cases so first of allif line I matches line J of my document remember that it's not really line J it's like making a document that just happens to kind of start at line J right it's like taking scissors well then I can
match them with zero cost right because the beginnings are in the same place and I can move my Tetris game down one and that's perfectly fine so uh right so case one I think is the easiest one whichis if a i equals B J right then I can just remove that line from both documents and move forward in which case I'll use my same goofy notation I'm going to get that x i j well I'mgoing to just increment I and J and keep going rightlike that cool Okay so what's something else I could do I could delete a line yeah so what happens uh
um so case two is delete a I right that's a different thing I could do to line I well now what do I have to do I have a document on the left hand side which is one lineshorter and the right hand side nothing changed but deleting a line cost me a dollar right so in particular I have that x i j well what happens well I got rid of one lineright um but I had to pay okay let's think about some other things um you could delete BJ
this case actually isn't in the solution because it turns out to be unnecessary um oh I'm only allowed to edit a oh in that case I don't have to delete BJ I really didn't read these problems very closelythat's my bad this would have made it much easier I really should read these things um cool so that like eliminates half of the cases of my notes fabulous incidentally you could do these things on the other directionand it really wouldn't change this problem a whole lot uh sorry you know I have this bad habit like when I'm reading research papers of like reading the research paper I wanted to be there instead of the onethat's actually on the paper and somehow it's a very similar phenomenon here okay right so uh great so I can only edit document a which means it's probably way easier than what I was worried about uh fabulous in
that case ah bananas um what's our third case here well um let's see I could also insert a line um let's see so what ends up happening there so I can only edit document a H so that makesmy cases different than the ones I wrote down on my notes um
sorry okay so uh
um okay so if I insert let's do this live yeah okay so if I insert a line at line I I might as well make it match BJ there's no reason not to right like I might as wellkill off one element of B while I'm at it yeah so if I do that what ends up happening well I still have to match line I I've just kind of moved it lower in my file but I'vein essence killed one line in file B by making it match this new line that I inserted in my notes because I thought I could edit B I said okay I can just delete the line and b insteadand somehow logically that's all easier to think about but but these are these are exactly dual to one another um so in that case I have x i j well I still have to deal with AI I haven't
gotten rid of it but I've matched line J so I paid one dollar for uh inserting a line and now I have that because I've gotten rid of a line in in the other file if I stopped hereby the way I would have edit distance but um unfortunately for me I have one additional case which is mild irritant as they say which is that I can swap rightfirst of all can I always swap I mean I can but if I swap two lines and they still don't match the lines on the right hand side I'm kind of hosed right because I'm you can convince yourselfthat in the next step I'm gonna have to delete something anyway swapping was free if I swap and delete that's the same thing as just deleting so it doesn't really matter so in particular what that means is I
might as well only check the swap if it actually helps me yeah so in other words if I have a and I have to be a little bit careful because I'm swapping so if the next guy in aequals B the current guy in B and the current guy in a equals the next guy in b well now I can swap this guy and kill off two lines of my files while I'm at it right soin this case uh I get that x i j well swapping doesn't cost me anything and I killed off two things so
that's the the the the recursive so if I were to write this out on my homework what should I do well I shouldn't I mean probably if you use this arrow notation I don't think it would be abig deal but but really you should should add a line at the bottom saying that you know I can choose to do any of these things so really my recursive call is x i j gets the Min ofall of these uh one two three four Expressions that I've written here okay
what if I have the first condition but not the second one ah so that's a great question yeah so the question was like okay well what if I you know I can match the next line but not thecurrent one well there's two different things you could do you could either make another case for that that's perfectly fine right in fact you could do that you could do you know that I matched the second condition notthe first one like whatever you can just enumerate as many things you want it all through and there's a constant number um alternatively you convince yourself that that actually is unnecessary here because a different so that's like swappingbut then one of those two lines is still a mismatch so you're going to have to delete something in the next step so you might as well just delete first rather than than Swap and then delete uh and
and so that's why that case isn't isn't necessary yeah exactly exactly so if you swapped and you killed a line then in effect I think it's a combination of case one and case two here if you kind ofexpand your recursion now but if you're having trouble convincing yourself of that that's fine just add a case here yeah any other questions I'm going to ask quickly because I this problem makes me nervous
sure yeah okay in the worst case if if we've done something wrong you can certainly add another case here um I'll think about it at home okay so uh since I've managed to pontificate too long let's let's keepmoving hereoh yeah the problem is it might have been used
and that's not okay yeah because at the end of the day the the files have to agree like you have to match B to a wow to the leads into inserts no no but the the Swap and deleteis illegal because you have to use both lines that's a condition in the pocket oh I'm sorry that's a better answer um so Jason points out that if I swap thing I can't delete it um because the waythe problem is written so that effectively removes this case otherwise I think I guess Eric is oh sorry I've managed to totally botch this which is totally unsurprising um yeah so so I think the problem also states thatlike if you swap the swap has to be useful um and that's why this this additional case that Eric is asking about where you swap and then you match one line but not the other is unnecessary you might
be able to relax that by just adding a case here but since the problem doesn't ask it I'm not gonna think about it okay right so under all the assumptions this problem that I didn't read but are veryimportant to solving this problem correctly uh uh I believe we really have uh uh written down all of our cases here um okay so let's let's continue with our sort bot uh Paradigm so now we have all ofour our recursion the topological order here is a little bit trickier than normal right because now you've got a two-dimensional array but it follows a pattern uh that's pretty typical here which is that x i j only uhdepends um on on other xijs with higher
I plus J right so I think about my graph of sub problems it always you know if I wrote this in 2D Matrix it always kind of points down into the right maybe um which is what's making ituh acyclic it's a very typical pattern in these sort of two-dimensional dynamic programming problem all right so let's see here sort bot so we need our base case uh this isn't too bad because essentially when you have boringdocuments they're very easy to match to one another right so in particular uh for any I if I'm at line n plus one in other words I have a blank document that I'm matching to document I well howmuch work do I have to do it'd a be little bit careful this is where the the suffix version of this problem is a little bit more annoying than the prefix one or if I managed to swap those
backward again um that in particular the remaining number of lines looks like n plus 1 minus I right um which is different than like in the problem is just I because they're working in the other direction in thesolution rather and similarly you need a second case for those two here right so you have X n plus 1 J is going to be n plus one minus J cool okay so we're going to continue with sortbot here um right so what is our original case kind of by definition uh is is X one one or zero zero depending on how you index and then finally what's our run time well uh let's see there'sn plus one squared sub problems and of course that's equal to order n squared the sub problems are just a constant amount of work so they're each with constant work
so our entire runtime is order N squared and hopefully by watching me be confused in front of you and think through this problem you too will see how the problem solving you know procedure can happen in your owndisorganized brains okay so that concludes our our sort of treatment of this this problem here that I think is the hardest one so so the other two thankfully are are much easier to to think about I thought umbut I never liked at a distance I remember seeing that in undergrad algorithms getting confused okay so uh the next problem uh problem three here uh deals with saggy mimson uh and she has a bunch of blocks andshe wants to stack them on top of each other that's what it does and as a young structural engineer she has a few criteria on her problemlet me go to the right page in my notes Here
right so uh so this is problem three uh so we have the Block B um I uh has size that looks like with w i by height h i by length l i I remember getting confused in elementaryschool about the difference between width and length all the time to me those always sounded the same but it doesn't really matter because she's happy to rotate her cubes anyway that that she pleases uh there's a key detailwhich I did remember uh to actually read in this problem uh which is that she has at least three of each type um where type here means that I can I can permute these three numbers any way thatI want because that's the same as this rotating a block but anytime she has one block that's like one by two by three she has at least two two more in her bag somewhere okay um oh one times
two times three is equal to six thank you Apple watch okay so uh that's odd so she can Orient her block any way that she wants meaning she can rotate it um uh and any any in any fashionthat you'd like and so what we're trying to do what we want is the max heightum where she's stacking uh her end blocks I suppose I should say there and blocks uh so she wants the max height that she can achieve but just to be kind of annoying um or because again she's veryconcerned with structural stability she lives in an earthquake zone she would like uh with the condition um that each block is strictly supported uh on the Block beneath that right um
so in other words like if this is the base of one block then the next block that's stacked on top of it has to be strictly contained within the block below it right so the problem makes sense haveI omitted any critical details I don't think I have this time this one's a little easier
oh yeah so and she can't do anything crazy she can't like do like a weird you know like balance it on its Edge kind of thing um which is Eric is absolutely right it could actually give her ataller uh Tower than you could get if you're only allowed to rotate blocks 90 degrees I don't think the problem states that explicitly but this isn't a trigonometry class so I think we're in good shape okay um rightso so that's our our basic problem here this is one of these problems that like it's going to be a dynamic programming problem but again similar to many of the things that we saw in lecture it's not totallyobvious how right because somehow she has this big disorganized bag of blocks you could imagine a universe where there's two to the n different things she could do right she could for every single block she could decide whether
or not to put it in her stack and then she has to do a bunch of other work to verify whether she can stack them while supporting the strict support condition or not so initially that seems kind ofannoying so what we have to do which again is is pretty common to a lot of these problems is is Place some order on it I mean that both in the entropy sense and also like literally we're goingto order stuff um and and in particular uh we'll see that this problem has a lot in common with that longest common subsequence problem that we saw in lecture increasing subsequent sorry um right so here's some some observationsabout our problem which are going to help um first of all when we stack our blocks we might as well always align the shorter side of the block on top to the shorter side of the block underneath it
right um let me draw a picture of what I mean
so let's say I have a really block whose base kind of looks like that and then another block which is also rectangular that I sit on top of it like that then notice I could so in this casethe shorter edge of one block is aligned to the longer edge of the other notice I can rotate it 90 degrees and it still supports on on one another so there's never a case you convince yourself with justa few inequalities um where I don't kind of always put the long side parallel to the long side of the guy underneath it and the short side parallel to the short guy underneath it that makes sense cool sothat's observation oneobservation two can I ever like let's say that Maggie actually sorry sat saggy actually had not just three blocks of a type but like 25.so she just like has hella blocks right she's uh my question doesn't matter the answer is no because um this word here is really critical which is that there's strict support right so your block only has so many
faces right and in fact um by by observation one really all that matters is which of the three types of faces is sitting on top right because we can just always rotate right so there's three configurations of everyblock so at most can any one configuration appear more than one time no because of the strict support condition right otherwise the rectangles would match up and that's against the rules yeah um so in particular oops the numberafter two is never after one is is two which looks like that um okay uh right so so in particular um there are only three orientations
wait this is just which of the three edges of the block is the one that's that's going away from the floor the normal to the ground uh and moreover uh each can appear less than or equal to onetime that's good because it limits the size of our problem uh and finally umoops well I collapsed the the two of the cases in my notes into one case here um but that's okay uh and in fact notice that the problem tells us that she has at least three of each typeso in a sense if the problem um if You observe a one of a block you might as well just throw away the rest because you know that you can use it at most three times and she hasthree of that block we can't use it more than three times so and since that's just Superfluous information okay right so um this allows us to to put a little bit of order here because notice that when I
look at the stack of blocks here what do we know if I look at the length of the long side and the length of the short side in the plane of the ground those numbers have to decrease onevery level of my block right they can never increase that's what the strict support condition says combined with observation one actually even without observation one um which is which is good news right um so this is what's goingto allow us to impose order on our problem namely that we can sort by The Edge lengths because we know that we we have this support condition okay so let's let's fill in some details of our algorithm
okay so right so originally already we can see that our list of blocks is kind of useless because the width length and height values are sorted in ways that don't matter uh moreover if we have more than threeof a given block that's somehow not super useful um so instead of that um Let's uh without loss of generality let's assume so w l o g here um we can always take our block and assume I'm goingto do this slightly different from my notes the width is less than or equal to the height um is less than or equal to the length Okay so so every block if this isn't the case I could godown my array of blocks and sort and sorting a list of three numbers is constant time okay um right so what does this allow me to do well I'm going to say that a block type actually is an
ordered set where the third number is going to be the axis that points up and the reason to do that is that we know that we can never use that more than once for any type of a blockyeah so now I'm going to make a new list of blocks
capital B because I like blocks um and it's going to look like the following so if with so if W is less than H is less than L then I'm going to take every block and duplicate it threetimes notice that I might end up with a list with like nine times of every block but we will fix that later um uh right and it's going to look like the following which is the okay I'm goingto have w i h i l i this is like describing a way to stack my block right because it's saying this is the short side this is the long side this is the vertical side yep and thereare three cases right where any one of these guys can be the vertical side right so there's one let's say that the H is the vertical side then W has to go before l so it would be w
i l i h i and a third one where the third guy is w h is less than l so it would be h i l i w i and those are all the different ways that I cansort of Orient uh these blocks in my stacking assuming that I um impose condition one for convenience here okay we're going to make a new list of blocks where I take every block in my original set and Ijust duplicate it three times this way after I sort its coordinates right and now um well what do I need to do well for one thing this thing may have too many blocks I might have a block that'sthat's repeated more than one time and I know I can't do that um and moreover it's going to be convenient to have this sorted because I gotta stack these guys eventually yeah so I'm going to sort uh that
list uh and I want to do it I can never say this word lexicographically meaning the I'm going to sort of the first coordinate and the second and the third
lexicographically um notice this length is 3n if I had n blocks to start with so this entire thing takes order n log n time which is important to account for um and then I can remove duplicates
I'll let you guys convince yourself you can do this in order end time an easy way would be to make a second array uh and just kind of move and only add stuff when when you you didn't seethe same thing before okay and finally now these are ordered in a really nice way right because I can stack my blocks but only ever looking to the right in my sorted list right assuming that I'm stacking fromthe top of my tower down which is I think sort of uh what's what's going on in this thing okay so now finally we can do our sort bot um and I might do S and R and Tand then allow you guys to think about the rest because as usual I'm talking too much uh okay so now um this is starting to look like a subsequence problem right because essentially when I stack my blocks if
I use this block here again if I'm stacking from my tower from the top down all the blocks that can sit underneath this one have to be farther to the right in my array because of the way thatI sorted now that doesn't mean that I can put anything on the right underneath this guy but it does mean that I know nothing to the left can go underneath this guy that's that's the way to think aboutit Okay so here's gonna be sore bus so s what I'm going to say is that x i here is equal to the maximum height of my tower and I'm going to taking a little bit of inspiration fromour subsequence problem that we've already seen I'm gonna I'm gonna force myself to use block I we'll see that's convenient
I and possibly
just for fun maybe we'll do the the prefix version of this problem this time um so now uh I can use any of the previous blocks right so I can use the first eye blocks to make a towerbut I'm forced to use block eye by the way I'm from now on when I use indices into this sorted array okay um so this is a problem obviously uh if I could solve for x I would bedone right because I could get the maximum height by just iterating over all the x's and choosing the biggest possible value here and the question is how do I do this uh recursively
so uh here's our uh recursive step so let's say that I use block I well because we we know we have to right um so in particular right we have uh now I'm seeing why they didn't use thisnotation uh in their answer but that's okay um
let's use another letter to refer to the third coordinate uh
yeah let's say VI is always the third coordinate so I've already used wh and L and I'm afraid if I reuse them after sorting it's going to confuse people um so v i is the third coordinate of theis element of my my sorted array that's fine okay um right so what is my height uh if I use a x i here well I get some height from VI and in addition to that I get whateverI I stack uh underneath that guy yeah um so in particular um I get that x i well I get the height of the block that I just decided to use and now what are all my cases wellI could decide to do nothing else like just not use any other blocks that gives me a height of zero or well let's see here I could use the X's but I have to be careful that I can
actually stack them yeah so in particular well uh I needyeah I I can take an XJ value but I got to be careful that I can stack it underneath so in particular um what do we know well I can do anything from one to I minus one rightbecause that's sort of the definition of x i but in particularI can stack it on top right so one easy way to do this is like it just array I I iterate through the first I minus one elements of my array and I just check my stacking condition forevery single one of them relative to block J right so in other words that the the width and the height or rather the first and the second coordinate satisfy the strict inequalities that I need I'm phrasing this sentenceneutrally because I forget whether this is increasing or decreasing but in any event um so what do I do I check all of the blocks that I could possibly stack from the index of the array perspective I make
sure that I could actually stack them thanks to the the size of the current block that I just decided to add to my stack um and I I move recursively okay right so this is great because now I'mlearning exactly the recursive scenario we wanted to be in right because X I only depends on XJ where J is smaller than I and that is exactly our topological uh ordering that we need if you do that onyour homework you get minus n for large m okay uh similarly uh what's our base case well obviously um if I only have one block I might as well use it yeah so in that case we have xone is equal to I guess in our notation here like that uh our original one we have to look a little bit careful because of the way that I've defined X because X assumes that I've used a particular
block right so I have to say well I might not have actually chosen you know the very last block as the one I want to keep um so I have to iterate I could say that really my originalis the max over I of x i right so one of these blocks has to be the block on top I'm just going iterate to over all the possible ones and find it and then our final thing todo is the runtime t um this one is the mildly trickier than the previous runtimes that we've done so far in our example problem in particular uh how many sub problems are there well there's N Sub problems orI'll say order n because I'm always off by one um
right corresponding to each uh Block in my my stack here but how much time does each sub problem take at least the way that I've written it here um well what do I have to do I have toLoop over all of the possible blocks and find the one that I can stack on top of and then take the max so there's a loop here from 1 to I I is upper bounded by n so thisis order N Sub problems Times order n work per sub problem so at the end of the day my algorithm is going to be order N squared and of course again I guess I had I promised it andthen I didn't actually do it to actually implement this algorithm there's sort of two different ways to do it right I could write a recursive call plus a table right the table is maybe initialized to a bunch of
nands and then I implement this function recursively but before I do that I say if the table does not equal Nan just return the value in the table and otherwise you know call this recursion or I could justhave a for loop from 1 to n and build up the table uh one element at a time and both of those are exactly the same from a runtime perspective okay so I think I've managed to botch thatmuch more than my notes or the written solution uh but uh the problem itself is actually pretty straightforward so if you guys read through the answer plus some of the I think actually the hard parts of this problemwere not the dynamic programming it was all the observations you need to get there so that's why I I spent a little more time there okay so as usual I haven't left myself enough time for the last uh
problem but we have a few minutes and and that'll be that'll be sufficient to set up the the I actually found the last problem to be easier even though it technically is sort of two Dynamic programs in oneum somehow I think the logic is a little easier okay so uh
I think this is the backboard yeah that's that's I was just realizing that this room doesn't work the same way as the other one uh yeah this is embarrassing you know I spent all day thinking about topology andthis is like a classic kind of you know problem in that Universe um Okay so we'll just erase one board at a time and I'll try not to write three feet um live this time oh this is probablythe one board I shouldn't use foreign
so right and our final problem we're given an N by n grid and on our n by n grid uh Princess uh Apple uh banana Plum Princess Plum uh right so here's our basic setup there's a big gridof stuffor maybe a small grade because I don't feel like drawing and and every grid Square can have one of three things you can have a mushroom you can have a tree or it can have nothing at all anduh our princess starts here and she goes she wants to go there uh and and and moreover uh there's a couple things that are worth noting here so first of all um her path is quick
meaning that she can only Traverse two n minus one grid squaresum to get from one corner to the other and apparently she's very into mushrooms and she'd like to accumulate as as many as possible along her path right that's the basic setup here so she wants to get fromthe upper left to lower right and uh in order to do so uh she wants to take a quick path so she her main priority is to be efficient but among the different quick paths she wants to pickup a lot of mushrooms it's understandable and not walk through trees thank you all right so like maybe there's some grid squares that are marked with like a tree meaning that you just can't go there that's a treeum okay uh uh right so that's our our basic setup here but the problem does it takes a bit of a Twist right it's not saying just could be the shortest path which should be very much like the
last kind of unit in six double o six um but rather uh the question is sort of what is the number of paths that she can take from one side to the other um and what is the maximumnumber of mushrooms is roughly the question asking at least what I remember from reading it last nightthat's so right so so she has to take the most number of mushrooms she can but there may be more than one path uh that gets you there that is quick that satisfies this condition in which case shewants the count of the total number of ways you could get from one coin to the other why you might ask why not um okay so right so uh you know so for instance maybe there's a mushroom hereum now there's a quick path that gets her there uh and collects one mushroom so there's exactly one but maybe if there's a mushroom there uh well initially it feels like maybe she could get two mushrooms right she
could go there go up pick up the second mushroom and get back but we're going to see that this quick condition actually uh allows it doesn't allow you to do that okay so in fact it'll turn out thatquick paths can only collect one Mushroom in this two three by three case so there's the at least two different paths well there's one two three uh different ways that she could collect one mushroom and have a quickpath okay so the first thing to notice uh your search is a little bit sneaky by defining quick paths uh basically by giving her no slack at all right um and here's the basic observation notice the in orderto get from the upper left to the bottom right she's going have to to go down into the right possibly she could also go up like she could try and go around a tree but only plausibly uh and
in particular the question is how many times does she have to go down and how many times does she have to go to the right well she has to get to the bottom of the grid right so she'son grid square number one just go down in this case at least two more times so in general n minus one times she has to go to the right n minus one times so what does that mean shehas to make two n minus two moves and that's a lower bound right so if she goes up she's going to have to go down again so it's only going to make it bigger right so at the veryleast she has to do two n minus two moves you know down and right to get from the upper left to the lower right how many squares does she touch when she's doing that was the fence post problem
right so she made two n minus two moves and she had a place where she started um that implies that just by moving down into the right she makes two n minus one squares she touches rather so canshe ever move up no could she ever move to the left no and that basically is all you need to solve this problem the rest of it's actually pretty easy right so so the basic observation here is youcan only move down and to the right because she moved up or to the left her path would no longer be called quick uh and that would be a problem moreover every path that moves down into the rightis a quick path assuming she was just their target and doesn't hit a tree okay um so that's the basic observation and notice that that already basically suggests it's like screaming out to you how to do dynamic programming
because literally you have a table looking at you on the Blackboard right now and you have an ordering like down into the the right the the the the the is acyclic yeah okay have I flammed on the boardenough times the first time I taught at Stanford they I got negative course feedback that I had too much coffee and was slamming on the board a lot apparently um I watched the video later and indeed that wasnot wrong okay so uh right so uh we're going to call K this is going to be the sort of the max mushrooms
she the can get going on on entire path in the upper left to the lower right so we want to know the number of Quick paths that can achieve this number kit okay so let's do sort by reallyfast because I got four minutes actually a tiny bit more than that because we started late okay so uh now the kind of annoyance here is that there's two different numbers that we don't know right one of themis K and the other is the number of paths right like the problem didn't tell you how many mushrooms she can pick up it does tell you that there's some path to get from the upper left to thebottom right there's not just like a row of trees somewhere um which I feel on my commute sometimes but uh it doesn't tell you you know the number that she has to accomplish um and and initially that's that's
kind of annoying so maybe the first thing that we do is just compute K like the maximum number of mushrooms that she can collect on any quick path and then we go back and compute that other account yeahbecause that would be one problem-solving approach so that we could think about a little bit um so in particular uh let's define okay i j to be equal to well we can generalize our problem slightly and say whatis the number of mushrooms that I can get on any kind of rectangle embedded inside of my full problem right so in other words this is the max number of mushrooms or M's for short on a quick pathto i j so in other words she always starts in the upper left but now she stops at any other grid cell okay uh because I'm running low on time no do I'm going to this the way I
want to do this no so we're just going to think about okay yeah so the question is could we compute Justice value K which certainly seems convenient like like you know Princess uh Plum really she might as wellknow her anime she might as well know the number of mushrooms she's targeting if she can if she can get it right um so how could we do this uh recursively well she has to get to position ij and from our argument up there she has to get there by either coming from up or to the left right the way we've chosen to write down this problem so what are our different cases well first ofall if there's a tree you can't do a damn thing right she shouldn't even be able to get there yeah and for convenience uh we're gonna find You could argue that it's zero um we're going to mark this
as with a special number and we'll see that that makes our notation a little convenient um so one is if there exists a tree then we're going to say k i j is minus infinity again there's a philosophicalquestion there does she get minus infinity mushrooms if she is standing on top of a tree I don't know because she shouldn't stand on top of a tree but at least it's it's going to let us know thatsomething went wrong in this grid Square in the other parts of our recursion okay um and otherwise well what are our different uh cases here well she always picks up a mushroom if it's there she might as wellshe's maximizing yeah in fact I think the problem even says that she's she's like really new mushroom she like collects them automatically right um so uh what do we get
I'll use unnecessarily fancy notation this is an indicator of uh whether there exists a mushroom at position i jright um meaning this is a one if there is and there's a zero if there's not uh sometimes this is a indicated with a one with a little subscript but whatever um and in addition to that she mighthave picked up mushrooms along paths and we know that her path to position i j either came from up or to the left right so uh in other words we knowthat she could have gotten the Max from any path ending a buffer or any path to the left of her so that's k i minus 1 J which I guess is to the left and k i J minusone like that and this can be used to fill in our whole table of K values in fact since I'm low on time I'll let you do the t-bot for the remainder of this problem right essentially I think
the key observation is this one right obviously when she starts the in upper left we get zero mushrooms because she's not standing on top of one the problem says that and this allows us to fill in our wholetable k so in particular this gives us our enemy now we now know how many uh mushrooms she should have at every step of her journey in fact it tells us a tiny bit more than that right becauseit says if I'm at this grid scale at this particular grid Square during my path I should have this many mushrooms if I didn't then something else something went wrong yeah um so the way that the solution iswritten they do two pieces of the recursion and once you actually could have just solved for this K Matrix first and then gone back and done the second half with this problem and those are are exactly the same
yeah and and when I was writing my solution this is the way I thought about it because somehow I kind of thought like she might as well know how many mushrooms she wants to collect before she starts countingpaths that's like a secondary question you know um and and so this is one way to do it so in our remaining negative two minutes um let's think about the recursion for computing remember that we want to knowthe number of paths needed to collect that many mushrooms uh the maximum number of mushrooms please let there not be a whole lot of stuff on this board ah there's not any stuff on this board it's great okayum so in particular now I'm going to define a second thing that I also am going to do dynamic programming on yeah I'm going to say that x i j is equal to and I'm going to make a
kind of a sneaky definition uh here which is the number of Quick Pass
um that end at IJ
with now let's anticipate our problem a little bit so at the end of the day we're going to do like X of n comma n because she wants to end up all the way down to the right andhow many mushrooms does she want to have now that we know okay she wants to have K of n comma n mushrooms along the way it would be kind of ambitious if she wanted to have K of ncomma n mushrooms the entire path um but it would be slightly less ambitious to have K of i j mushrooms because somehow that's exactly what we we just uh constructed in in the previous thing was path right sowell the last guy looks like a Max now we're going to expect to see some plus signs here because we're like adding up how many paths we have okay and now let's come up with our recursive rule for
for this uh array X and then we'll we'll call it a day so in particular gun one if there's a tree
how many paths are there there are no paths because I can't get there yeah so then I J equals zero okay otherwise there ain't a treat and now I have to be a little careful right um so I'mgoing to write this like a little piece of code um you could have written this as a giant Max instead and there are a bunch of cases uh and and whatever so let's think about it like a pieceof code so initially I think there are no paths that get me kij mushrooms that's perfectly fine and remember we're going to keep applying the same piece of logic which is that a path can only come from tothe left and up and let's uh think about those two cases um and by the way we're going to use Chi to equal this Chi of stuff that that we had in the previous expression right um so Chi
is one if there's a mushroom at this place and zero if there is not okay so my path can come from the left or up I know that it can't come from Up if the number of mushrooms thatI got from Up plus potentially the one that I got here doesn't align with the number of mushrooms that I should have by the kij standard that I have set for myself yeah so if I if I wantto write that out in code uh the way I do that is I say if um K of so let's say I look to the left first you know this is like you know look to your left lookto your right one of you will pass this exam kind of scenario and I potentially add a mushroom at my current position if there is one if that is equal to k i j well what does that mean
that means that path that went to the left were able to collect the number of mushrooms I need to get to the position I am now so now I can add
what well all of the different ways maybe I'll do a plus equals X of I minus 1 J right because any path that got to the previous guy and clicked the right number of mushrooms can now reach meand get the right number of mushrooms and similarly I can look up and do exactly the same logic so if K of i j minus 1 plus this number is equal to k i j then x i jgets an additional number of pathslike that and now I do think it's worth spending eight seconds thinking about our base cases uh here because initially when I first saw this I panicked a little bit because it kind of looks like this should justend up giving you a bunch of zeros right because like I'm just adding values of x's to themselves I don't have like a one plus anything anywhere which is kind of weird if you think about it so all
of the reason why the positive numbers appear in this problem is from the base case which is kind of cool I think um it's like I think one of these things where if you anticipated a problem then it'scool and if you didn't anticipate the problem to begin with you just wrote down this formulas you probably wouldn't even think that it's interesting um uh but but in any event uh what is our base case so we'llwe'll do the b in sort bot um so first of all um what is K of one one remember that's the number of mushrooms you can collect by starting at the left square and going nowhere and that's zerobecause the problem says there's no mushrooms in the upper left what's X of one one well this is the number of paths from one one to itself that collects zero mushrooms so that's one OK and I think that
the rest of the sort bot table here isn't terribly uh difficult to fill in um so notice that in in a kind of a funny way all of these were Christmas steps we're just adding one to itself abunch of times um but of course the way you do that the reason why you get a number that's interesting is because of all these if statements and the fact that you can add two different pluses coming fromtwo different sources okay so I actually do encourage you guys to look at the code in the the problem solution because I think it's a nice example of taking this recursive formula and then unrolling it into like iteratingover a table and that's a useful skill that I intended to do today and then didn't actually do uh very carefully um but with that as usual we've gone over time here so we'll call it for the day
uh and I will see you guys when I see you guys all right