DP Ravi
DP Ravi
DP Ravi
mic pre-sequisites.
Bottom up -
Recussion
① Tabulation
-
Ration
TCOIN
SCT0IN) +
a
o
section assay
station up
have case to the required
Sie
Ideclare dp (n+i]
② base cale TCOIN
favz
dpl0] 0 =
-> SCOINS
dp[T 1
=
-par
⑭space improvement
③ recusion relationship use two variables instead of assay.
& (i=2; i n;it=
it TC3
o(N)
per:
(dp/i]=dp [j-1]+dpfi-2]; pevz:
i-2 890(
↳ ain= por+kevz
3
plevz: por
Now:
cust
↳
-
ID problems
9
-> it's a problems
count the total
① rum of ways
⑧ min) maxoutput
possible best
all convers
By ways
jump
① Why the greedy doesn't work here
out
wing peedy you miss some
can
significantjump in Future
10 20 30 10 03
2 3
O I
Reussion
-
48
index
based
① that index
⑧ do all staff
on
⑨ take the
min (all stuffs)
4(n-1) ->
energy required to reach (n-1) from 0
Kindexlindex == of returno;
-a(index-1])
Ilindex-1)+abs/a/index]
left:
is[index
Cindex-23)
Sight=4/index-2)+abs(a(index]
- a
60, 50]
n6
memorization
=
10,
[30, 10,60,
convertthis recursion
to up
40 SCOIN
(5)↳ TCOIN),
=
&(4) 30(1)
=
-2
) 20 =
/
() 30 =
&(1)
Tabulation
- (4+1)
-40
↑(i) ①
I
decleue
fill the
dp: A nay
base case,
10
0
dpC0T
=
-abs(a[i)-a[i-)
=
ifI to at
③ Dos loop,
left=dp[i-B -a[i-2])
iPiss=dp[i-2]+abs(ali)
light
left, sights
min(
Tabulation space optimized dp[i):
TS30(N)
T20(w)
seOl S-OINS
-
Follow-up ie its
is it2
umps t
↑H,
i+2, i13,.......,
otimize from
wecan sla(K)
TC20(NEK)
SCS0(N)
iP K= 4, 4 variables are needed to
stone last a values
iPatination is notneeded
Let
got
of
recursion
ecided
conceptof
means
notickieat
it
&(ind) ->
olen
9 ilind==of return ainds; ice
returno;
i lind col
Plind-e);
pick:a find]
+
notpick 0+ Plind-y;
=
How optimizeuss'
to b problems, memoire the
TC50(N)
S-0(N)
egdens
5
here, first I lastcannot
be together since it's
adjacent
TCe0(N
S2OLN
-
10 50 I dayo -
5 100-days
"761
greedy + 50+
here
fails
Recussion greedy
--
n 4.
-
=
Daiossible wass
greedy
sion
⑪andstuffon index the
fing
problem
sub
dy 10,1,2, 3) ↳> to
initialize thebeauties
are
N 4
1
dP(N]/4] apassay
--
(Nx4) size
is"ut4
(bottom-up
Tabulation
-
the similar size of assay space
-
optimization
declare
Or
d[n]/4]
base cases
② -
(aCo][r], a(o][2))
d40]C0] max
=
⑧countpaths e
with obster
③ path
min sum
④maxpath
sum
⑤tangleastfront o
ita
count all ways, use recursion
I
ways?
How
-
to write securence 2
terms
in of ex
①express everything Now, column)
0,0)- (m-1,n-1) & do all duffs
on the index i, j
ormic
③ sum of
allways, max
↑(iii) -
are
5iR(i d
Tem
= 0
=
&& i = =
seturn 1;
·'
up leftH2, is
12
= 3
&(0,2)
potent
ayeit ↳ plants
is left
&10,0
↳PH, ⑱ >O
40,e
->
- ,
⑤ Check is answer is
TCe O(NXM/
xms
See
and +
DP
M-1
Tabulation (bottom-up) Los /i 0 = ->
- -
101 ->U-1
<n] 0
I declare, de [m]
=
0) dPC0J10] 1 =
&dj
Sin/i
=
=
=
= 0
② declase base case
left 0
dse
=
=0,
1 up
dp[o][0] =
D(j)
dpsi)(5)
up
=
+
di-
dijell
I dp[n] 0
=
n-1)
- stand 9 dos/j 0
->
.- =
SiP(i = 0
=
&&j 0) == d4[9T[] = 0;
elses (i-B
[37+d4[]
Si = dp/i-
TC-0 (MXN)
(j-
emp/i):dp [j7 +terp
Sc-0(N up-tamp
its
Recession
- mization
3
3
Tabation
optimization
⑱
2 2
ec not considered
summation
is
Base cases,
ithis path
-
-
INT-MAY;
iP(ico ";<0) eturn
up a (i)[s) + 4(i-1,5)
=
Icompare (iii)
paths
mination
② explore all
min ooth
⑧ takethe
treation -m)
Tc-0(N
0(NxM)
Stolpathlength)
>
↓
(M-/AN)
"ulation optimization
2)
getting
ending point point a variable
Fixed
①-- #x
2 3
6 7
3
10
8 96
the
try paths
ession -- as
① representin (i,i)
② explore all paths (14)
③ mix of all
youths
resence
will startfrom 10., (40,0)
sowlany
column
to last
path sum from 10,0) hum of coll
110,0) min
2+st...
to
TC, 2
↑(i,i)
return a(n-i[s]; SC-0(N)
s ip (i=-n-ll ;
downdiy euny?
diagonal-a[i](s]+P(i+1,;+1;
setuen,min (down, diagonall
3 dp/i][5]:
memorization
-
dp[n][n] ·TCT
St
·cat-(a)
Tabulation space optimisation
-
tease dp(n] (n)
Lasliosis,a(n- (s
⑪
2 3
0; i- 7
is 6
=
Pos(i=n-2; 3-7
3
10
=;i
=
0;
896
"Los I [j]
aCi3[s]+d4(i+
=
I
only psev
sow
9 /st need
-
d=
+dSi+D
(iTs]
-we
assentsaw
down dg min(d, dg)
a =
E
diagonal dp (i)(s]:
I Re
E
dp [0] /0]
setwn
N
TSY O(NY
SCT
0(NXN) TLE
nation
TLE
Talization optimization
Falling path sum/variable starting a
ending points.
-Max
⑭ by outall ages
secursion
-
in terms of Isi
express
① everything
write base case
I
all the paths (NY
⑧ explore
⑤ max
among
all fraths
Memorization
not
- memorization
secussion - overlapping ->
a
sub problems
↑ I ↑(ii)
S
'iP5011i M)
declare dp[N][m]
return Number.
if (i
Max.
=
0) unaid[i];
Negative:
⑰v) P(n-1,3)
==
if (dp(i][i]
[i][5] + 4(i-1,j)
->
let =a
Lt1d=a [i7Y]
+i-,3-D:
R(x-1,2)
A(n-s,) let ad a(i)(3] +
4(i-1, IH);
Almo, 0f
=
0/NxM)
=
TCT
2n,I): + O (N)
$ (iii)
S20(Nx M)
to reach
Miss - may puth sum
the firstrow
cell in
from any
↳easence destination
-have
care,
butof bound
-
t
at in
↑
insist cases
-
[Y Colo
or col?M
↑(i,,)
return Number.
Max.
Negative:
as iP(sc011is= M)
if (i 0)
return
==
a [o] [i];
,d);
setuen Math. Max (S,Id,
3
TCT
3N exponential
TE 99 O(N)
Tabulation (bottom up]
-- d$[a][M]
I
① declare
of away d/[0] [1] aCo]/]
0 em-1
for (i
=
base cases
=
③ observe
I for (j=0- m-1)
3v a/i][s]+d4[i-1(c)
(i7+dp[- (;-B
=
iP(-10) 1d a (1)
=
1d, 9d);
(M) df[il[]=MaxCu,
0 (N
+M) 0
+
3
TOS
SC 0(wxM) E
mayi=df[n-D (ot
&(1 1 =
- m)
dp[n-y/s))
maxi:max/maxi,
return moxi;
optimization
e
cusing
pering,
Go 1i = 0 em-1
(1)=a[o]/)
↳os (i 1 4-l
=
-
por
(sty
iR(st1cm) id a (i)(5) + D
=
#fil[)=MaxCu, 1d,ed);
c
freu=as
,
mayi=df[n-D (ot
&(1 1 =
- m)
dp[n-y/s))
maxi:max/maxi,
return moxi;
TC 0(NxMS +O(M)
SC2O(N
memorization
105
Recession 105
utation spacerization
essy
pickup, DPOn GRIDS, 3D DP
-
3 1
3427
5535
ans
12 97
+
Alice Bob
path
setwntei]I:
combos of
Ieturn 3x3= 9
-
iP(i 4 =
1
=
(i];,Ii
(j]; a [i]
5 iR (5, 5) return
=
[i][j2]:
=
3
Maxi =
0
-1
to + 1)
Pos(d
9 dos (diz - to +1)
5,+dj, ju+die))
(i)()+Pit,
->
maxi-nax (maxi,
a
de
3 Maxi;
setwen dp [i] (;,][iz]
=
satun maxi;
-
3
TC (3Nx
3N) - exponential
967 O(N)
·zation
isis (in
↓ ↓
↓
N M M
de- [N3x/M7x[m]
states
([j][iz] aumber of
different
ToO(NxMyM)x9,
+O(N
3- P/NxMXM)
cussion
Ration
roization
21
21
Tabulation
-
I
Los (3x-0 to mil
I Posli2 =0 tom-1)
for (i n-2
=
to 0b
to m-l
9 hos (5 = 0
to M-1
9 Pos(s=0
E
, 21
optimization
e
-> two
vasicebles
ID dp
ID alp
2D alp ->
2D dp
3D dp ->
et sum equals to
target, identify CP on
subsequences
subsequences/subset
subsets
contagious (non-contagious
subsequence -
assey -
0,2] -
[1,3,2] -
X
-
12,i] v
v
[3,2]
check it of gives
them
all subsequences I any
-> generate
a sum of K
set
Ms power
M2 - secussion
(index, taelf
Recursion
everything
= in
① express
ofthatindex
② explore possiblities - a [indax]
the
notpastof
asindex] front of the subsequence
subsequence
ure/false
Plind, targetf
Sip (target== of
return taue;
024)
(a(0) tgets; TI
iPIind==0f return
==
Se O(N)
bool nottake: I lind-1, target
bool fale=false
find]/
target: kind-1, farget a find]);
a
of -
take=
Tage
103
ind < 103, target =
(NY
=
ind target TO +
i
[103+ 11
dp (103+17 x
Plind, targetf
return taue;
Sip (target== of
0f setwen (00]== targets;
stargets
iPIind==
bool led taint", asdlinds
bool fale=false
if (target:
take=
a
findand, target -afind]);
(0]]:bue
di[O] [a
② ni)
0
%os1 =
->K)
3 dos Starget.=1
E
I
3
secusion memorization
tre the
zation
tabulation space
option
te tree
tec
Co, 2, 3, 4]
->
anp(4)[T]
(target) not
- [3,2,73 iP81=0, we are
picking
in subset
original problem
-
vxv xv
anything v x V
- ~xvvx 10 11 12
I
total sum:A
51-012345678
3 2 0
10 9 75
S2512
81=
6 8 12
92 =
totalsum-s1 abs di- 1288 2 I
aus=
2
anse
↳
(3)
in terms of find, targets
① express
all possibilities
② explore a retren
asks count the possibilities
question return ⑧ sum all of
->
in base case, alway
0 I
OK2Y)
oS
<=taryelf
iP(afind] -- pick:
de [ind] [tasget]
setum pickt ootpick;
mization i
TC O(Nxsum)
0(wxsums O(NS
+
Ste secession
Ass
tabulation
-
①write base
cale
Pos (i 1- ntl
=
3 Loss 0+ Sun)
=
E
seussence
3
TC o(Nxsum
S-0(NXsum)
3
Reon 3
memoration
iP (ind 0) S
=
=
return
adnumco]==of
2;
if (sum = 0
=
num/o]] returns;
it(sum = 0
=
II sum==
setum 0;
3
b) 91)S2
(11-52
=
St fotalsum-s2
S2-S2=D
Totalsum -
D 2x52
totalsum
=
I
=
⑲g
Tatal sum D =
s2
=>
=
=
where target
↳ countof subset
Totalsum -D
51-S2 D -
=
-
3
5,2,6,4) 6
easel of Num(i]
=
46,4355,2) -totalsum-DI0
be even
10.7:3
⑤ totalsum hasto
secussion
spaceoptimization
I
o of knapsack I secusion to
single assay space optimised approach
Recession
-
out all combinations
try ↓
take the best total
Value
combination
AIR
P 60 ↓N
1(1,6)
&(1,2)
/40 IN /040N
My 40404) w
& [ind, wi
& iP (ind 0) =
=
W
Sit (not [o] <wI return valso]; It
2.
passess ind, w
changing- Si
de [N] [n+1]
TG-0(NXw
S->0(NXW) +0(N)
ASS
tabulation
-
cases
①base
in loops
⑧ changing params
③
Copy the recusence,
ind>
to no
nots 0 to w
dp (N)[w+Y
0
=
Recussion
13
memorization
13
Tabulation space
optimization
· sow
optimization
local minimum coins, infinite supplies patterns
-
ack.
--
eindwillsemain
ane
Rocussion
-- TC-012 exponential
I (ind, target SC
0IN
I in <ind== of
num[ind]) ==0) return target/rumfind]
, iP/target
-
letusn MAX-INT;
3
notpick:o+ Plind-,
targets
pick:INT_MAX
1+ I (ind, target-aum[ina])
pick:
iP( numfind) targets
return mathmin(pick, notRicky
3
memorization
-
ind, target
di[N] (target 1]
+
S-O(NxTarget) +
Otarget
Tabulation
-
case
① base
params ind, I
I changing
securence
⑧ Copy
dp[a] [target+1]
Los (T= tasgel
0 ->
if (T% af0] = 0)
=
dpCo][T]
=
T/ago)
ele
INT-MAX
dpO] [T] =
is
Ration 3
memorization
optimization
Tabulation space
3 3
sum subsequence
(1, 2,
ass= 3, of
tage;-'I
end
f
it i
way
⑲
/
⑲ Se
(2,3) (0,0)
- -3
(1,3,1)
-
(2): 3
51-52: target
se):
Difference
factionized
G
23. count
change, infinite
supply problems
Recursion
-
①express in
lind, target
② have cases
③ explore all possibilities
a nature
④sum all ways
To exponential
& (ind, IS
See O(targets
I inspect anfind]==0) return, deretuno:
I 5) -
memorization
not take:Alind-s,
take:O T-Afind]) changing params, ind, Target
take Pind, Id
iPansind] IT)
-
take O font 0 to t
return take- not
I OCN][FiT
Tabulation TCD OINXT
-
dp[N] [T+
S20(NXT) + 0
(fast
Dalton? (Tanso] 0)?1:0;
=
ind<n; ind+1
dos/ind=1;
9 dos IT 0; = T(target; +++)
3 nottake= dpfind-1][T]
[T- a [inds]
take:O
iPasind]c=T) take=dplind]
,p[ind] [Ty taket nottake
=
Saturn di (n-1](value)
24 unbounded knapsack
Recussion
-
lind-1, wS
I
nottake 0 +
it
N al eval ( i n d] + Ri n d,w -wel i n g
=
Nata l ,
take=
incoffing
ice exponential cause
we are standing
atsame indusi
SC50(WH
memorization
-
not
ind,
&(N] /r++
Tabulation
-
case
①
Base
indepfont
⑧ ps,
w- o to not
⑧ the secussance
Copy
eclusion memorization
↳ 27
tabulation of space optimization
27
Todos optimize is
it to assay
5- Rod
cutting problem, Dassay space optimised
Recession
-
⑧ setwen of
max all possibilities price obtained?
&(ind,w) 9
↑Plind== 0) (Nx price (0]):
setusn
I
P (ind-0, NS
notiake=0+
INT-MIN
take=
sodlength=ind+1 [ind] + kind.
N-sodlength) than 2m)
take-
iPsodlength N) nottake
==
peice
exponential (greates
To
max/take,
seturn
S27 O Hargelf
I
Memorization
-
ind, N
dp/N] [N+
TCe O(NXN
0 (NxN) 0 Hasgelf+
SC-
ASS
-Tabulation
write base case
①
② Changing passes
③ recussner
dp [N] [N+i] NxPrice So]
d4[0][w]
=
40s (N = 0 G0w)
Pos(ind=> 1 t0 N-)
Ros (N 0 to N
=
sacusrene
socussion memorization
12
12
olmization
space
Tabulation
12 12
optimized
i
12
longest common subsequences) DP on strings
S1= 'adebo
32 = "doadb"
comparison
strings Ireplaces/edit
*
Brute force exponential the
-
a compass
on way
secussion
subsequences
I generate all recursion
->
write
cules to
(indi, indef
index
and / ced ① express
in that
possibilities
*
on
all
② explose
9 index
them
de de ③ take bestamong
Ge 10....2) I
P12,7-> los of stil
Sts2 (0....2)
and ced st110...2
Steels....)
R2,5) e &
secssence
match on indexes
·+ I(indl-1, inde-o
② not match
Minds, inde-11
ofmax (Hinds-,inde), exponential
2", 2m
↑ (indi, inde TC
567
9 ipindo co indeco)
setueno;
iP (s[indi) 52
==
[inde])
seturn of Pinds-1, ind2-1)
indes, Minds, inde-1)
seturn ofmax (Rinds-1,
3
112,4
Iced 2
and 1+1
=
=>
It So,
0
agenpeo
2
acc 4+ 1
gla
de
↓ 410, -140
ke
·pos R10,0
Bale
Memorization
- &st2 [0...... I
R(i,i) - has of stilo.....1]
dp[N][m]
=
-
1 TCe
88-
OCNYas OLNs
+
Recession
memoization
tion;
3
bottom ups
dp [N][m7
0
&
=
↑
&10) ALU) &(4, MS
Pos (i 0tON) dp/i]/0] 0
=
sightby s
=
it to
Pos (9 050m) dp[0][5] 0 =
shifting
the base
=
case
so
- P
return
Rob (i=1J0N) 94 (ico "5 <0)
Ros1 1toMS
=
will
--
become
119 =0)
setum P
iP (i
=
!
=
=
secussion
3
ulation optimization
3 3
I M
i a;
=
&do
·tile (iso
⑧ S2[5-D)
Mox 3 iP(Sti- ==
⑧ O
Max 3
Sindex)
index--
=$1[i-i;
i --;j-;
[7>dp (i3[5-1)
be iP (dp(i-1
si/i-1
#
=
S2[5-
=
9i =
i-1;
e
dpi)]=max/dp 3
I
Do I let i 0;ic=4; itt) dp[i)/0]
= 0
=
.
longest
moon substring (not subsequence)
si= abod
abzd
s2=
optimizatio
tablation space
backward
palincome
6 =
bbbab- ab I
bb -
lobb
⑱)
** * *
bab v
are
⑭- generate allsubsequences
I take the longest
⑫- 51- given input
si
S2-> severse
⑳- es
Tabulation space
opti mi zed
4 4
leverse of p
S:abo ad
↓ insections
abobad
you approach?
do intact
the palindomic
longest postion
keep
-
ext abo ad ren75 codingninja
*
a
bo acba codajniinjadoc
datinized
space
6
site operations
S2= "AUC"
⑭o delete everything from
fromseto-413
"
② insecteverything
total: operations
M
max operations:4 +
↑ insections
deletions
nC
abcd a
↳
edeletions
invest subsequence
My- longest
common
les 2 2 +
3-2, M-1Sx2
=
ansz 4- H+
i
=
4 -
7
-
4
m
3
=
-3
tabulation
les
-
32
- shortest common super sequences
Si= "brute" s2: "Soot"
"Autegroot" length: 10
length 8 shortest
"bgeuoote"Y
-
=
S1:bleed 82:blue
ans-bleved
t
beute 9500
***** *****
=n+M-lenlles)
-string=?
I- S O O A 1cs([+][m+D]
g
it I 2 345
O O O ⑧ O 00
b 10 O 0000
3200 1 I 1 I
u 300 l I 1 I
+400 1 I 12
2500 L L I 2
I- alter
S O O A be
will
it q, 2 3 45 this
outside
white
while
another
-
000 case
O 0 ⑧
look ↳
in
↑
-D B
O 000
ND48
-
32 O O I
-
u 3 O o D DB 1
85
+4 00 1 I
te
stovorby
Ggbsovote
len
ee
magonewd
⑧
bgeoote
3- distinct subsequences (ID assay optimisation technique.
concept- sting matching
try out
all possible ways
babgbag
Si=
52:
bag
Recession
babybag ⑳ --
(ii)
①express everything
in
thatindex
babybag ② explore all possibilities on
start1, m-1)
M Mul
of
-> of distinct subsequences
number
32C0.....] in $10..... I
base case
↑(i,)[,4(;<0) return 1; -
bag
if (i <0) retano;
s2[5])
babybaya I
is (81)]
=
+ R(i-1,1) ob
return 1(i-1,5-1) j = -1
is matched
else ↳everything
setwen R(P-1, ) it all class of 2 matched, return o
3 not found
is io & iso-match
TO exponential o setwen
see
52-2m
S-0(N+M)
memorization
aging prasamse
ij
p [N] [m]
TeONYe) OSN e +
auxiliary space
menoization
Recussion 5
5
lationup dp/N][m]
① declare up assay
the index by
1 to sight
base cases
shifting
⑧ wsite ① dp[at] [m+i]
for changing params 1
⑧ write looks (i=0coaldp[i](0]
=
② tos 0
40 (8=0f0m) dplo][]
the secresence
④Copy
=
③ Posli=1 toul
④ rac-sciyyedpliiyis
dep (i][5]:dp[i-195]
up is initialized with
↳ because o
already
setunn dp [n][m]
Tabulation
5
optimized iD-optionized
space
5
5
-Distance IID
Assay optimised
① insest
② remove
replace intuition
③ ->
same
horse
10S semove/delete
& I stayed
↑
--
I j
hosse SOS
etos
doesn't match, update ↑ I
;
i i-1
doesn't match, delete,
=
j j -1
=
1:If
1 -
P(i-1,5) i fli-less
+
jI
=
matches.
- (ii)
&+P(i-1,
it iPlico) return it;
return it1;
iP(jc0) Ri-1,5-1)
cases exhausted return of
iP (s)i]==S275)
exhausted return Math.Mix (1+R(is-1)
PLP-Is),
↓+
we
need to insectsemaining it 4(i-1,j-1))
chass from S
exhausted TC - exponential
it
*
match
means already SC- 0 (N+M/
found S2:" Memorization
"Lor"
81= -
samsi j
to
convert
min
setoperations
3
changing f N M
required dp [N][M]
TE O(NXM
x 0(NxM)
+OM
Recession
2
menization
2
Tabulation shifting index sightby
to
E -
I j
·
nt1
ot
U M
r
·
Tabulate
--
spacetimized
2
↳5, wildcard matching ? -matches
with single character
infot
saDODe
-
Bug S1- lowercase. 3. A
S2- lowescase
51 xxabod questions check whether si matches with
Awe
=
52 or not
32:abod
ab?d
-
S1-
false exponential
52 ab
=
TCP
-
Recession SCONT
① express in (i,i)
② explore all comparisons
it
⑧ outof all comparisons, ↳or * cabe
↑(i, (inis)/Xst
5
PCOads?of esteem be
en
ablabdel ab*labde
14(i 2 0 =
&& j<0) de ........
Sii]:"?"
q
-
iP (S1) ==
52/i] /
abx/ab
seturn 4(i-1,i-1) ablabde, -I
a
abxlab↑
iP (S1(i) = *Y
ablabd *Y
=
81:"***"
81:
" "
3 92= 52 =
Are falle
Memorization
-
i j
M-1
Or
dp[N][m]
TC-O (NxM
Sce0(Nx M) + 0 (N+ m)
memon
tiue
Reation
Be
Tabulation
-
X based
indexing
fie
Tabulation
tie
spaceptimized
Awe
n6
[7, 1,5,3,6,4]
=
ass(It
buy? I
sell - E
profit=>5
intuition
-
if you as selling on ith
day,
price from
~
the min
you buy on
Thail
*
st -> (i-1)
profit 0
=
we min=alo),
1; i <u; i++)
Posli =
I cost a [i]-min; 5
(profit, costs;
=
profit-max
min-min/min, a (is)
return ofit;
& sell stock
⑬Buy
u6
[7, 1,5,3,6,4]
=
als[It
want
buyd sell as many
times as
you
outall ways.
my if
Recussion
①-
a
flag to see we
a
buy current
can
of Lind, buy
everything in terms stock not
excess
a
1.
2. explore possibilities on
thatday
made
So take the all
max profits
④
Base outof found
buyings-piace-I
case
his
toke
0
41i,i
2
5-7 =)
-
+flice->
+
iP(ind n)
==
selling
->
returno;
Plind+1,I)
iP(buy)
profit: Max ((]+Kind+1,0S, lot
ne
not take
take
ebes +Plindta4);10+Pindfl,a)
sofit-Max ((pices(ind]
I
return profit;
TC 2"
SC-0INS
emoizatnbry
dP [N][2] Recursion
-
6 ~
TC 0(Nx.2
SCR0(Nx2) +OlN
mization
6
Tabulation
-fN+s(2)
-
basecase
da
not too
0 to 101700
buye
rabulation
6
~spacetimization
space optimization
i
pees [5,35,0,05,
=
5
->
ex-2
-- -536
profit 6.
may
==
initial call
tansactions x
-X 2
10,1,2 boy:1s we can
buy a stock
today
&[ind,buy, cap ioe
boy, we willbeinvestmoney
return reduced
3 iPlind= 11 cap:=of
o will
money
80
0
=
from profit
ifwe
letiofit=
buying today,
0; are not
I
Max the
0- we can sell
todaystock
0 +
ind cap
Ofont buy, ollk
N2 3
4p(N][2] [3]
TCe 0(Nx2x5
SC O(Nx2x5) +
ORS Recession
6
6
Memoration
Tabulation
-
dp(n][e][3]
⑧
0
:
not necessary is
since alloy
->
8
with
Base
-
cases
initialized
it's always
⑩pindd bry can be
anything -atcap:o, from
start
I
ton-1) so
Dis (ind 0
= -
0 tol)
Pos(buy =
dPind] [buy]/0T 0 =
1) Tabutation
Pos /cap=0 t02]
<plu)(boy].[cap] 0 =
6
starptimized
6
asactions
sell are allowed
k
psices:(3,2,6,5,0,3]
= 2
g
O sell stocks with cooldown
buyd
buy sightafter
cooldowncan't sell
->
unlimited transactions
memorization
Tabulato
Il
⑭I tansaction
a sell stocks with fee
buy
unlimited transaction will be taken
bansaction a fee
butfor every
Lee 2
prices:(1,3,2,8, 4,9]
=
-W
5
from let
I -
2 .
Dee
-
2
5 3
+
8
=
↳fee
⑭42- longest increasing subsequence
(Is pattern)
ass [7=[10,9,2,5,3, 7, 101, 18]
18 ben4
2, 5, 7, -
Butee
T2
U ①powerseenin
Recession
-
term of (ind)
1 express everything in
-111 assfind]>
as [per]] perind
iP(peor
[NT [W+]
==
lettakelen: 1+
4(ind+1,ind) dp
index
coordinate change(shifting
the
setwen max(notTakelen,
takelen);
↓ -o sight by IS
3 defind] [pert=
TC30(NXN
S-0(NXN)+O(N)
XC0,-1) 10,9,18
my Is Inattake
& (0,0) R10,-1
d mit
Rasion memorization
-
3
3
3 -
point longest increasing subsequence
question
Tabulation
-
0dp(u)(n+] 0
=
initialized
② since up already
is
need to write
don't
with o, we
base case direction
③ clanging params,
opposite in
ind=4-100 -
ind- to
per=
follow cordinate ship
④Copy the secessence,
tabulator spacoptimization
3 3
-> T6 eOINY
=6 - 0(N
fake
5004 to 2
3
orespondant
- it's
same whetherdat 16
"
-
is
Or index of 515,11I
of index
2 -
of
index of
5 15,6)
11 (1, 16)
ingate i
max
s
value s
hash-
n
not ee
value
vale
16
in
->
- 11-5
3
dpe indexI
val(2] ->val(o]
OCNY +OINS 185
ofor
=
TC 2
Six O(N
TCT
40
5, 11,16 # -> use
to
binary search
search) optimize
leck4t LIS (binary notpaint
-> we can Lis
by binary
saasch
not
Notes in interview its
referable to rewrite
an
1, 7, 8, 4, 5, 6, -1,9
·1,4,54,6,9
T6-
0(N*l o gn)
S
O(N
I
subset
⑭- largesible
size
51,16,8,43
-
answer -
orders
pointthe answer in
any
ed 1, 4, 7, 8, 16
ex- 1,4,8
if 4 is divisible by
..4
08..
..
0(NY +O(N)
ice
SeO(N
16,8,4, 1
longest
string chain
words):I ', b, be, boa, bda, bdca]
-
quence -
-
notsubsequence
for (i=1 to as
9 Ro (1= 0;j2;; it
indlass(i],
as[i?) Id
dp [i]+1> dp(i))
dp [i] dp/3]
=
+1;
S
max:
max/max, dp[i]
3
return max;
e(aus),ass(i)) an(s):boa
as[i]=bdca &
AA A
*** *
pointes
is both the exhaust together
it's a match
in it
i can have one skip
TCS O(2xlength of string) to
(logiosting
So - 0(N)
3
Leckiebitonic
subsequence
12 1
2
bitonics increase thedecease 1
or, decease
then increase 12233
22'
3 lette
os, justincreasing 3
os, justdecreasing
*
1,3, 7, 12,9,4,2
10
9,6, 2, 1, 4, 7,
5, 2,17
j
10, 4/
as II: [1, 1, 2,
&4s from left
2 1
2 3 34
dpICT:12 1 -> 45 from sight
332
1524
dp2[7: 6, 3, 1
3, 6, 5,
1,6,
bitonic islength: was added twice
3 7 6
= =
(bcor, 10
4+
-
equal
to consides
value
in
I
e
Lis
Olm
O(2++0(NY.
TC -0(N
↳8- number of longest increasing subsequences
4 T
5LS
I 35
#E3 *2
423
dpl] +2+ ans
-i
+
it
countC] "-H 1, 7
1, 4
1,3
G,3,5 1,3,4
1, 3, 7
1,3,5 it
1, 3, 4, 7
4
it
1 2H= 3
2
2
-Maxix chain multiplication (MCM/ Pastition P
ABC A 10x30
:
B 30X5=
C 5468=
I
-74500 Mix up - 4500
·
(ABC
Y
30x5460
② A( ->
I
27,000
=>
n an]e[18,20,50, 50,0]
N5
=
BT 20x
30 2nd - ACI ACE=
/ABC
,(()B543 ft
Pastition DP Rules.
I startwith
entire block/asay P(is)
2. ty all pastitions all partitions
-> Run a loop to
by
3. Return the bestpossible
2
partitions
<10 20,38,40,50]
A B C B
i j
A ↓
&11.4) ->
I
return the
in multiplications tomultiply
matix 4
matix to
↓ based
start
&(0, n-1) where does; I
out
noter we have toReguse
on the question
Kit
iP (i ==I cturno;
min=INT_MIN;
+
[i-D* als[]
'Stos=(an
min:min/min, steps
3 memorization
return min; -j IDEO(NY)
->
memorization
-continue for lecture
Tabulation
d<[NYN]
PoS (i 1; =
ICN;it
dii]/i] 0
=
I
I Url to
=
to Url
j it=
tabulation
8000
lecst-min costto cutthe stick
re
cutsisas feeangle ene
sosttheassaub'trobes independently
insest 4:7
index of 2 3 454
insets o 134 57
I
i,j
i
initial all TC
exponential
& (1,4)
-
S-0(N)
Flipeiss min:INT_MAY
atumi
& (ind= i to]] +A(i,ind-l+ind+,I)
[cost=cuts (i+1-cuts[i-
costs
min:min (min, 4,3,4, 5
3
retaste min;
itste/51
77 3 4+ 3:17
+
,
·!!!" 4
-I
M!!"t
·, ,
-
ind++
-
ind+t
Recession
10 memorization
Memorization
--
I I
Hocuts to cuts
1]
dp [+] [c+
cesize of alts
look
O(xc
-Ol
is
ice
0(
se0(x) +
Tabulation
-
10
iabulation
lects burst balloons (pastitionDP coins?
a
3X/X5:15
[3,x,5,8]
I
[x 1,5,8] /x3x1 3
=
3)5x8=/28
(*,5,8] (X/X5 5
=
[3,4,8]
1x3x8 24
=
↑x548 48 [5,8]
$5,8]
=
148 x 1 8
=
1x8X 1 8 [*]
[*]
=
-
-
56
⑰
total coins =
->
go in reverse, start from last
P 3 15 8 I element
-
-
-
gr -> 1X8X1: 8
3 -> (x3x8= 24
->
5 3x5x8:120
↑ -> 3x1X5=15
(b) be 8 b4b5b6]
I
ind
⑧
↑(i,ind-) +Plindt,I)
I
(max, costs
4p[N+i [N+]
max:Max
I
return max:
Reclusion
120 120
memorization
Tabulation
-
dp[n+i[n+1]
have case
-
Por(i A ton)
=
Ros (j 0
=
tons
iP (ixi) dp
(i] (j] 0
=
(write
in opposite)
dangaiable
1
4 to
9
to n
j51
securence
coly
Tabulation
-
120
10253
-
evaluate boolean expression to tur
Or I
expression: 'TITIF"
->
& and
XOR- d
evaluate the
Find number of ways we can
to true?
expression
intuition
can do pastition
-feresy apesand
a
we
independentsub-problems
I
I break it into
->
opeland are atdifference of 2
Ten
T
I ↑ I
TAF F
justoperand
=
it
FRF F
operand
=
ps
TaF
& (indt is
ind T
=
indus FRT T
Ali,
=
sight
left light
a left a
↓ ↓
Ta =
TU2
=
total
ways: axy F U4=
F R3
=
where x-fue
denum of ways UIXR4
where the
↳- num of ways y: &3 XR3
when it will be true
left I
↓
sight
TC2 = CIXR2
Td
=
dIXG3
=>
F=R4
F U3
=
E U2xC4
total
ways:
↑10.4-1, rum of ways to make the
iP(1 I) =
=
SLT P1i,ind-1,1)
=
LF P1 i, ind-1,0)
=
RT P(ind+1, 5, 1)
=
RF Plind+1, i, 0)
=
iP (a [ind] = '&1
=
the
ways:
else iP (afind] ==
"i)
ways
else
return ways
3
TCS exponential
3- O(N)
memorization
Ti yo
dp (n) [N] [2]
TDe
(NYNY2S NTRe
Sy
Recursion 2
memorization
2
single has is a
palindome
every cuts (n-ll
itself
->
in
de
string- bablabobald/de
ans= 4 4 patterns
temp:"";
SCHO(N) state look
min INT-MAX:
= memorization
- -0(NXNI
1031;=1;34; ++) I
To
call stack
exceeding
both are max
Tabulation
--
&dp(n]
dp[9T 0
=
care
② bare
i url too
③
=
securence
④
Copy
tabulw
I
55 Pastition assay for max sum
Ipsont pastition
-
Max 3
elements
in a
pastition
&
(id)id(ind
MaxAn8:
n) returno;
==
INTMIN;
INTMIN;
fres
MAX=
low 8;
very the
action for from
=
+)s
Posis-ind; in mink, indic);
len+t;
max:max/max,
assi
thatindex benx maxt P(T+)
the bestpastition
sum:
③ take maxAns:Max Isum, maxAns
3
(1925 107
3
return maxAns;
exponential
*
i 1 k
TC-
lenz lons
law: Se
-
Memorization
o tout
dp [n]
TC- 0(N/ x 0114
Sc-0(N) +O(n)
Ass
-
Tabulation
-
0
base case dp[n]=
ind=n-1 to 0
securence
copy
Recursion memorization
120 120
tabulation
120
↳6- max
rectangle area with all I's IDP on
rectangles.
used
may of
I Nanalieas
&84-
histogsaminte
man
⑱6
I
TC - 0 (N *(M+N))
S-0(N)
locst - count square submatives with
all ones IDP
-
on
rectangles.
O I 2
I O 10 P
↑ ↑
1 2 2
↑ O ↑ P
↑ 2 02 3
↑ I
at
sight bottom is
&p (i) [si]
↓ end at Liss]
zisi how
many squares
three
minimal of all
A ↑ + himself
↳
-> I + 1 2 =
dp[i][Y]=min(dp/i-1][17,
(j-1a dp [i-D
dp[i](3-1) +1
TSe
0(Nxm)
88
O(N+m)