Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

DP Ravi

Download as pdf or txt
Download as pdf or txt
You are on page 1of 91

Programming

mic pre-sequisites.
Bottom up -
Recussion
① Tabulation
-

② memorization-top down fond to store the value of sub-


problems in some map/table
Fibonacci number
# --

overlapping sub problems


do thi
↑ caseedp [nti

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

count allways ways


shortcut
of index
ify to present the problem in terms
statement
index as
on that
to problem
② do all possible stuffs
all
③ sum of all staffs - count ways
all staffs) I find mil
min(of TC0(N)

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

return min(left, sight


S
sub problems.
overlapping
-
2 3 4 5
01

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;
=

return max (pick, notpick);


3

How optimizeuss'
to b problems, memoire the

RIP -> sun blw 0 to index

4) -> sum bw 0 to index 2


menoization secussion

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

③ Find may/all ways

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
=

dp (0] (0):max (aco][0],


afo][23)
max/a/o]/0], afo) (is)
dp90]S27:
(a[0][0], a90] [r], a90j(23) 0(Nx4x3)
[3]
dpSO] max
= TC-
Sc ->0(4) 2011

octurned in the
⑰return whatyou
initial call in secussions
secussion (or, the

TC- 0(Nx 4x3]


Sc-0(Nx4
↳DP on GRIDS/2D matrix
-

⑧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;

insiconical (path length)


see 0
return 0;
+ in
up:1(i-1,j)
left:1 (i,j-1)
up-left;
I return
optimize recussion
-
useap (memorization 112,4

·'
up leftH2, is
12
= 3

&(0,2)

potent
ayeit ↳ plants
is left
&10,0
↳PH, ⑱ >O

40,e
->

- ,

dadane dp[m][n], initialized with


recursion call
② stove the result,
thatyou are
returning from
not
calculated
already
a

⑤ 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] =

iP(i 0) <up=d4 [i-1] [5]


in to look [5-1
⑧ State all states it(jo left=dp/i]
write + left'

Copy the recurrence I
,pSi][s]=up
01.MXN) 3
TC
30-
30(mxN) ↳stern ap [m-1(n-is
otimization it
space column, spare optionize
few
- we can
a
->
is there is a few row

D(j)
dpsi)(5)
up
=
+
di-
dijell
I dp[n] 0
=

emp't dpn) M2 temp(n) 0


4/1 Pos (i 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

-
-

0) return [o] [o];


(ip/i
a
=
=
0 &d j = =

INT-MAY;
iP(ico ";<0) eturn
up a (i)[s) + 4(i-1,5)
=

left: a(i)[s] +41i,5-1


stwen minlup, left
S

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

↓max path sum


is
any cell
sow
from
last sow

⑭ 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
=

Math. Max (S,Id, ,d);


setwen df(i)():
m-1) 3
do (s 0 ->

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];

let [i][5] + 4(i-1,j) I:


=a
4i-,
let1d=a [i] [T] +
let ad (i)(3]+4(i-1, IH);
a
=

,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
=

② write ↳os 4-l


(iii) a connect looks
to (i 1 =
-

③ observe
I for (j=0- m-1)
3v a/i][s]+d4[i-1(c)
(i7+dp[- (;-B
=

iP(-10) 1d a (1)
=

iR(stim) id a (i)(5)+dPi- (its


=

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

I for (j=0- m-1)


30 a/i)[]+d() per
(;-I
=

iP(-10) 1d a (1) (i7 +dD


=

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
+

fixed starting point ->


vasiable ending
point
paths by Bod
Max (All paths by
Alice +
All
sussion
Passion & (izit)
fesses (in,ji)
in destination
①express everything
cases
-> I out of found
& write base
all posibble paths
XNY
② explae
③ Max Sua RIP
↑ (ie, I, in, j2) ↓
1132 m) it1,9 it, it
3 113220
<
it, 5-1
iP (9010 11 ji m
==

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]:
=

else return a (i)(5) +a

3
Maxi =

0
-1
to + 1)
Pos(d
9 dos (diz - to +1)
5,+dj, ju+die))
(i)()+Pit,
->

"PIs, =je) maxi-max/maxi, (52]+P(i+, jitdijetdi))


[i7/is]+a[i]
=

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
-

dp (n) [m] <m]

I
Los (3x-0 to mil
I Posli2 =0 tom-1)

base &iP(j, ==je) dp[n-i) (j0]


[i2)= grid (n] (91), (92];
alt
ele d[n-i)(ii] (;2]= gid(n-1)(i)+gid[n-1
E
3

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=

return false as not take;


3
Memorization
-
state

outthe
figure changing

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

return false as not take;



3 dplind]/target]
Tabulation
-
dp [N] (target]

⑧cases [i]
tave
(07:
0-n-1) dp
101(i =

(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

subset sum 4Puences


prequal I

S1=S2:totalsum/2 -> five

is totalsum -odd -> false


Bue;
-> iPlan (0]
KS
<= peev[as [0]]:

tec

set into two subsets with absolute difference


l pastition min
a sum

Co, 2, 3, 4]

1,2 & 3,4 517-31:4


2
13 & 2,4 -> 1- 61 =

1,4 & (2,5) -> 15-51:0 us


fabulation for subset
sum a target

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

2018 counts subsets with sun k

[1,2, 2,3] target s5


-

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

Alind, targel Recession


TO -
sctuen; - S60(N)
S iP(target== 0)
return (afind]=:targets?:
0;
iflind 0)
==
return up [ind](target];
->
iPIdp[ind](target]!=-1)
not pick: I(ind-I, target,dp
pick=0;
Rind-, target find]) dp
- a

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

⑧ look atchanging parametess &

write nested looks


⑧ Copy requence
Sarget
dp(n)(sum+]
Pos(i 0 -n
= dp/iT90]
0)
=
1 =

iP (a9o] <>) dp/0][aco]] I =

Pos (i 1- ntl
=

3 Loss 0+ Sun)
=

E
seussence

3
TC o(Nxsum
S-0(NXsum)
3
Reon 3
memoration

tabulato space option


di Presence
lesss,
-
count partitions with given
the above question, the constraints
ase
II nums[i] (1000
in
I
target 1000
↳ O I nums (i) (1000
the base
modify
need to case
we

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

&express everything in of index


tesons
f

I write base cases


(ind, WI

⑧ explore possibilities
all say weightwts 3,2,4 (n-, o
pick a not pick val- 30 406O
③ max call possibilities 100, 70,30
inde 0 1 2

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.

else return o; Sc-0(N


notTake 0+
=
Plind-1, wh
take= INT-MAX
valsind]+P(ind-o,w-nffind])
iP(wtind) w) price: =

retan max (Rick, notpick


3
memorization OTN-P
SO -w
- ↑

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
-

outall combos to find target


bying
d min coins
take the combo
thathas -

ack.
--

infinite supply or multiple supply

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]
+

TCe O(NX Tasget

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
-

Blind,wine (r)* val i

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
-

① explore in - Lind, N) -181,


possibilities not take AY, NS
I
-
all
③ explore -> Take
till index, what
is the max

⑧ 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
&
=

are wettenbe negative


① declare up assay
② the
Copy
base case
for changing
②basecases
⑧ nested looks index
parameters
Copy the
④ securence
iftingof the
q
dp[N+i)[m+1 A
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

⑭27 printlongest common subsequence


len: dp(n][m],
index:
bent
/i=0toben-1)
is
8=
' for

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;

dpG][] dp [i-1] [j-B


(:-3[s],dp()(.) elee-j-1;
= 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

loc2-longest palindromic subsequence


is it eads way forward I
palindsomer
same

backward
palincome
6 =
bbbab- ab I
bb -
lobb
⑱)
** * *
bab v
are
⑭- generate allsubsequences
I take the longest
⑫- 51- given input
si
S2-> severse

all ICs (81,54

⑳- es
Tabulation space
opti mi zed
4 4

- min insection to make


sting palindome
insect
you
can
any
has
anywhere
s = abs a a Max
Ien(s)
abadd operations =

leverse of p

S:abo ad
↓ insections
abobad
you approach?
do intact
the palindomic
longest postion
keep
-
ext abo ad ren75 codingninja
*

length) 3 legth? It 11-5 =6


calindrome palindome length,
west I min insection
[5-5: 2

a
bo acba codajniinjadoc
datinized
space
6

e min insections/deletions to convert


string
to
A
string
S1= "abod" convert 51 to 82

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

bgzuooteip chas matches


taverse both
sing, both
take it once, else take

=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

③ summation of all possibilities


babybag return
gar
babybag Y babgbag
babybag
yS2=bagp

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

delete all from sen


insest all fromse to st- m
total operations (uton)
~Mis
find operations
Ha-1, MY
I
min
to
to convest silo.... it
32/0....] insection so inserts
at
->
sOS
hosses
a
i d
inaction; matches with
after
-
replace 1 Plis
+
the inserted was,
I9 1
= -
so

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

Si= "?ay" Are


*
- matches with sequence of length 0
S2:
"say" or pose

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

anyone can, retwen fee ↳b* abdef

↑(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
=

return 4(1-1,5) or bli,j-i)


is 0 && ISO abxla
ablab,
=

setun false; "ab" a a

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

best time to and sell stocks/DP stocks


6 buy -
-
on

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

less - buy a sell stocks II

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

if(b.1: (-pice(ind]+4lind-1,0,cald boy: boy


we can tomorrow.

mobit remain same

Max the
0- we can sell
todaystock
0 +

Hind+1, 1, cabl meviously bought


else it increase
it all
sell, of
pofit=Max(Ricefind]+Rindt, I, capy, & we can
buy tomossow
Flind +1, 0,capl)
of if notsell, profit remain same

& not boy tommossow


profit;
we can
return
if we sell, itsansaction will complete
3 & now cap-cap-1
TCs exponential
SO
memorization
-

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 =

②is cap a can be anything


Pos/buy 0 to
=

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

2, 3, 7, 101 -> lan 4


subsequences
various subsequences - print all

Butee
T2
U ①powerseenin
Recession
-
term of (ind)
1 express everything in

2.explore all possibilities


or take not take
take the be take a nottake
So max
length
index of peer dementwhich was picked
Alind, peer) from oth index, whose
RO,stast- lengthindex of Lis starting
per
is -1 -exponentieach
cal item
24 L Dor
Alind, per
return o;
TJ we are
Tare)
doing to
9 islind==al SC-0IN)
it (dplind] [pert]!=
"I) refunds.-- to h

let 0+ R(ind+1, peers


not takelen: memorization"
--
tont

-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

create new insted


away, a

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

then 8 will be divisible by


-
ans [1,4,8,187

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=

① (ABI - 104 30x5

I
-74500 Mix up - 4500
·

six8 10X5460 &

(ABC
Y

30x5460
② A( ->
I
27,000
=>

[10x30] (30x50) 10x30x60

n an]e[18,20,50, 50,0]
N5
=

A - 10x20 1st - ACO] A[1]


*

BT 20x
30 2nd - ACI ACE=

C- 30x40 31d -> A[2] *ACE]


DB 40X 50 ith- A[i-1 * A [i]

/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;

&02/K i t0j-1) P(K+)


-ass(i]) +R(i,k)
=

+
[i-D* als[]
'Stos=(an
min:min/min, steps
3 memorization
return min; -j IDEO(NY)
->

Syse exponential Up (3 [w] 0xwixo OCN


ice
87
sc-0(NXN) +O (N)
Recession
8000

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

a [i- xafind) xa/5+1] +


↑(i,) TCS exponential
3 iP(is]) retuno; max:Iot min SC-0(N)
->
islook
for (ind= i toj), -
memorization ↑Ce 0(NxNXN)
= O(NS)
x afind] x a [5+ j
cost:a [i-1 SCP/NXN +O(N)
ICON
Pli,ind-1) -Rind+1, i)
HON
- A86

(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

& (ie, is true) E


iP(i<;) setwen 0;

iP(1 I) =
=

9 iplistine == 1) return ai]=='T';


else return a lil==F';
ways=0 ind:ind+2)
ind I-1;
Roz/ind: it;

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
=

it listine ways += LT *RT;


IRFxTE)
(LTXRF) +(LFxRT)
+

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

4Palindome partitioning-1(Front pastition

single has is a
palindome
every cuts (n-ll
itself
->
in
de
string- bablabobald/de
ans= 4 4 patterns

i, loop -> palindomecheck


K(il
O(x N) +0(N) exponential
Sip (i = = 4) returno; TO

temp:"";
SCHO(N) state look
min INT-MAX:
= memorization
- -0(NXNI
1031;=1;34; ++) I
To

temp +=s[I] Ito


N
S-OINT +O(N)
iPlisPalindrome (temp)) dp[N]
cost 419+1);
1t
=

min: min(min, cost


etwrenmin;
this
albltemove
e
Recursion memorization
↑ ↑

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)

You might also like