0 ratings0% found this document useful (0 votes) 72 views104 pagesDynamic Programming
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
TUTTE LLL
%
PHEBDD
wae
Scanned with CamScannerJ
TTT
»
ih
y
=a
+
EE
=
=
er
or
a
wn
wr
er
“Dyponic_ Hogamming*
DP= Enhanced Recursion
Cfane)
Gund) ferction -eatles calls self with
Smaller inputs
= Poreut of Dynamic Programming is yecursion
— DP asks for optimal Solation
— Choice / choose — Recursion can be opplied
~~
Recursive >» Memoize ——> ate
function op - down) Bottom -up
ov
ini DP problems : .
O-1 knapsack (6)
Unbounded knapsack (5)
Fibonacci (7)
Longest Common Subsequence(/5)
Longest Increasing Subsequence (jo)
kadane's Algorithm (6)
Metrix Chatn jMuttiplication(7)
DP on Trees (4)
DP on mainx (4)
Others (5)
©
©
®
@
©
©
®
@
®
®
Total prrblens/ Variations = TI prblens
Scanned with CamScanner0-1 knapsack. Problen
i] Subset Sum
2] Equal Sum partition
3] Gunt of Subset sum
4] Minimum Subsel sum difference
§] “Target sum
§] Number of Subsets with given difference
Knapsack — problem
a IN
Fractional oft Unbounded
Greedy ) knapsack knap Sack
vrpbier qT rh 3 Ty
Paget 8 4s
yol(]: | 4 5S 7
we 7
( capacity)
Scanned with CamScanner
(Gea ele Ue i PTT ss see 1c nwSS aT Ul
be taken.
s nok biapeaal, pradtion o item Om
in qyactional Fvapsack, fra cde that tom of
But in oft knapsack, ether we have t
exclude the item
4p unhounded knapsack,
Flow by laenlly 8
we can take multiple instances of few.
wit}: | 3 4 output : Bottom -up
eee (Top- down)
°
s
TLELLEELCLLUEUe U0 8 & vom
Dp ® Recursive
+
Storage
VUUUTV TTA
Scanned with CamScanner° O/4 knapsack Recursion
Tnput ~ | wtl) = 7 3
Vv
Itemd.
det s qi) ™ x
if the weight of the item > the capacity of the bag.
Can't
Con take con't
take take
int ‘iRefBcHe(int wilt, int valC] » int capaciyp, int ») §
7 Base Condition
if (n==0 Il capacity ==c)
sretuin 0;
shee
if (wt[p-i] <= capacity)’
return = max( val oi} Knap sack(wtival y capocity 2 wt (0-7,
ny;
qT pspsosdossaee
> knapsack ( wt val Capacity ,n-i)) 5
ase if (wt (n-iJ> Capacity)
sretuin knapsack (wt, Val , Capacity, n-1);
Scanned with CamScanner
aaaaaaayHow to think about the base condition 2
Liild, fe. THNK Boul Vie base Conaition |
© Base condition —> Think ef the smallest valid input
Oo} knapsack top-dewn—A te:- Meni zation :
So th the recursive knapsack the
Variables that ave changing =)
PUTTTVCTTTLG
i
Knapsack (wt, val capacity, n os. '
F (wt fr-1) > et
one Gators a pseek( uti val Capacfty, n-(); i
an
4) copacity
Se qpr these variabla only, we lave to
ae prepare He tabi.
=
= krapsack (wt CI, val], capacity, »)§
~ wut dp(nai][capacty +1]; ytd
— memset (dp, aaa: y i
_ Tntibaton of ON
ae fable with * Z
> = -
3 - Wt dpfios] i004) da's ‘ne. foe conshaints
nee memset (dp, -1, sizeof (4); capacity 000
<_; it knapsack (jut wICJ, ik valCI, it capacity, int Df
iF(n==0 Il capacity ==0) rein 0;
a Vi Cap [n](eopacity] t= -1) .
~ yer dp (0) Ceapaciy] 5 {
a #Cutlr- ae caret i
vw aN i
science vee) + manage hve stapes: eto)
w
iv
Scanned with CamScannerCe. SS aE
- Bottom - up Approch
Tn this only table is there
Why bottom-up approach is best?
EJ amenrininet ore ea Sees
Cawe it avoid the enor of stackoveytlow evr.
3 Rearsive —>Rc coll
Rc + A
aeaG46.)
> Memoization
a Bottom - up —_
step i! Gnitialization
Sept
Sep2* Reuursive | convert this! tovotive
Functions relation
ntl
»
nee
SaaS
Scanned with CamScannerExample :
E wt] = ']3 a]5 ned
valfi = {7 [+ |s5 [7]
wed
wt=6
_—_——+ INITIALIZATION
Z.
wo wt | *
‘Lh
Be | +} 3 “he Z
Se| > 4 Ka
'
pe EY Max progit
a
—
~~ wt [1.3.4]
> val = (1,415)
= G36
al wh
YF o ° 2
~~ duitialization is_tmportaut
al Ag ee Z 9 ls “1 topos
a While Gnverting the ‘recursive cals to the itevative
= ‘elation ...
rr S Then the base condition of ecursive calls
~
ae changes into
ed
vw Initialization in the iterative
vr So|.
rT
rr
fl
Scanned with CamScannerbbebeberbbbdbibhihahkhabababbebt
oe Tterative
if(n==0 Il W==0) for (iz0 > 1cn4t 5 1t4) F
vehn 6; for(j-0 5 Jewt 3J40F
if (i=0 [I j==0)f
f (wt(e-"] <=) f
torn rnax [voll] + Krapsock (wt, val, We wr
lenopsack (at, val, W, 1-1) & ony
dp liIGI= o%
3
;)
(ust [p-i] <= w)
apr] = max/vatfes] + dpCr-DOW- vel], |
4p lr i) Go
else if ( wt{n-J-> w)
vyeturn Knapsock (wt val; Ws m-);
ae ACTS
Spd = 4p6-1 60;
Scanned with CamScannerUVULUULLEUCECCTUOCCOLLUUULE TODD PETTY
(ode :-
int fmapSack (int wt], int voll int o. iat w){
Vector Ap (nt! 5 vector dint ey
for(int iz0; Tents itt)§
for(int joi jewt + j++) f
if (is=0 Il j==0)§
op CAG = 0%
5
}
3
for (int iets ientts itt) §
for(int jot 1 JEWHI 3 jHHDS
if(wel- <= 7) §
pbIGa Sf] + apCi-A[j- wt,
; epCi-) (51);
else §
dp LIL] = tp -OLjI-
}
}
peu ae(rfv]i
i
Scanned with CamScannereee aeeeere eee eee eeeeeeeee ee ae
e Subset - Sum Problem Pare
——— :
1
Given an Orray :-
awl] § 2,3,7, g, 10}
Sum = 11
HF a Subset which having the sum of i elemed 1S equal
to the given sum then yeturn tue.
Here > subset= {3,83 S digi
Sum sil
We o1e Naving the choice to j
include the elume
exclude the elément in the Subset , we
onC] = [yal az] spo} sum=n
If we compae this problem with tre knapsack,
thew otra] [wid
Jp vetun pre.
WT
TT
mA:
ve 4
dp (n+i][sum +1]
— sum
4 § 67,8 Sou
> 3
Fle|rietrtete\r fete
°
- 2
Ta14]
ey
©
we w
\A ala a
L
Tf size of anay 7=0
still We can creak with Subse! cum=o
LGuphy oabset J
Bu if the avroy o} size ==0 and Sum >o
— Then we can't creat Subset
— Se Tuitialice with ay
ze
Scanned with CamScannerPRLELELEEEDLLLELELEELEEUOOLECEEECECECECOCODS
for(int ico signet s itt)
for(int j=0 5
JSSumtl 5 54) §
if (i=20) 4
jem = false;
iF (jes
} dp GJ (jJ= true;
5
3
0) §
\w— sum
ia
ooo
— TTT yet
chee Lo
ake we ae thallgwed]
3 dp (n +i] (oun +i}
Scanned with CamScannerKoapsack Subset = Sue
(we (i-i] cap)y BCmtr-i] <=H)F
HOC woe CG we 4pCIGN= AptrI(;-awfi-1]
ap G-AG9 M"
else dpe] GI;
dp GIGI = dp §-JG else
apGIGI= dp O-IG1:
eal sul ss >
Scanned with CamScanner4
© Equal Sum fastition Problem =
Epo! Sun fort a
Given an amay , we have to" find boo aiff
Subset such “that sum of their elements
Should be Equal
Flow
© problem statemet
© Strilay with subset sum
® Odd] Even significance
@® Gde Vari ation
ane [[Link]]
ofp 2 Tras
f19083 fig
s+s zl "
AA
—> The basic condition is > if the Sum of the away eluments
,
L
> . pees
- ig evens Then only we can
divide the array
~_ Else we can't do the partition i
> |
ar int sum =0; |
> for(int zo 4 '< Size 3 i++) |
= sum +2 av(Ji
t
if (surgg| #0) —> return false;
UD
arr= fess 134 ——> sum= 22
Now for Equal pantition TA
" "
so we hove to {ind the subset whose
WW.
swn is ll bee] Tato subsel
‘sum
So his problem now is conver!
problem
VUUTT ECC OCC eed
Scanned with CamScannerif (sum ==0)
vetwn subset Sum (arr, Sum/2)
for (iwt i=05 icns itt) §
Sumt= art (iJ;
5
if (sum/2 Io) retum fove
if (sum /2 seo) vetum SubSetSum (aw, sums);
Scanned with CamScanner
MEE ELI IP ADD DDD 0 erorne.UVTI
PUUULLELELOCOCCOCOLGCEE
Cont of Subset with a event Guu :
put
We have to count the number of Subsel with the
aw (J = [2, 3,5, 6,8, 10]
Sum = Jo
given Sum.
LeIsTs[¢ [3] |
Sum=lo {2,83
$2.3, 5} } fon ©)
fio}
awl] = f2, 3,516, 8, lo}
Sum = lo
t(nt][sum +1]
0)
> Sum
Oo! 2 3 £ 5 ¢ 7 % 9 Jo
0 | Po Ye Vo Vo | \¥o|% Fo \Fo ro
mM
2171
3/7) oF1F]
® T WT ee
pean ee ——> _ oto=o
‘So Gn Hof Subsets with given sum
we have to add both Param eters
re.
Scanned with CamScanner—
VUUUUETUCOCCECECECCLEULEE TEE U LEE
an[j= |i fe
output = 4
SitS2_2 Swe —> Equal Sau partition
e.| S)-S2 50 |
But in thio question » The difkerence (absilute) of subset |
Should be minimum |
Sn the above ex cumple.
the cures having the wWieimane dlifference
fl.6. 53 4ng
I+64+5 "
(2 W
C2 -1) — @ a Auwwer,
Scanned with CamScanner[Tie
problem is similar to Equal Sun partition
oy) fer eee s]
Now Wwe have to find the rouge of po cuw of,
partittona
Sum | Sua
WHAT COvLD BE THE RANGE P
Either Subset 1s
: a s Her co
Ae or Subset having oll
the elm euly are
eeian “I
Poe the range is [0, 23]
of Sum
é[s[«
Gaal asia 8888.)
daw
fin io de
o 1 28 4 FT RAN ee ERIE
Scanned with CamScannerCame You counst wake a subsel of Ie |
m gine a whose sur jo (© I
e So Now ¢ind out How ae eubies on tue nuuber Lac |
Salto tu ceuclition a i
Means can we make S) OS, om jhe ervey
ATTN
1
a
at
v we
Q
OS
oS
XE]
ita
©
\@
\®
6, fs. = §o.1,2,3,7, 8,9, 103
Tie D'S
—_ ©” This amay Consists both Sy and Sx. if Sel thew i
®(Saw-1) 3 1s abo preset > ie. 9
if p22 > (Saw -2) —9 is aloo prreoeut >
523 > (zan-ay—a()is ato preset so
cur See 5
we Sy
TTT
Su
Scanned with CamScannerRB US
So bosically we love to gind te only one partition,
another pabtition will automatically olepiined
CSi- S2.)—> minimize
FP (S2 ~ Si) 5 mimic
(Rouge -S.) -S)
[(Ronge - 2S] Minimize
Range is rating but
Cer
ae
add pI II 333385
3 ee -&
ot a = ji widitiad
(= 26, ] 3 Mininsize
Zar
Scanned with CamScanner. | 2
a ad 3
Je onl
~ jock —— similar
eae tal Tr sun J
ve pees ie
What does His block |
will tell 2
dize of aero = 1>$1 3,
Sum =
Se this problem «ill
Solved by the coe — |
It will chee heer |
we ave geting the Gu |
i
ao 7' er not
\, 1, L v L [, GV
Scanned with CamScanner—————————— eee
FP Subeeb Sul int anf], int Rouge ) f
o 2 3 4¢ s ¢ 7 &§ JF
Scanned with CamScanner
AIAN TAT O25ath Cat “vedo ‘opt chal
- Seawe - I waut to
Sh Stove Smalley
vale
Cs) |
int mint = INT- MAX;
for (int iso 5 [Link]) j i++)
saini=_min (mini, vecliJ)s
$ mini = min (mini, Range -a-*vecliD))s
a
velurn mini;
Scanned with CamScannerthts Giz] [3] 2 493-4
a
©) [Is] Giz] » 4-3")
occured
2tmes So
ie « tate of
AAS cabled diff a0 “dlf,’ 7
a
sum(s.) - sum Gf) = aff |
sum(s,) + Syén (Sx) = Suu an)
2sum(s,) = th £ Sum(ar) )
3S
> Asum(s) = afb + sum (arr)
KO)
€9°®
sum(s)) =4
Scanned with CamScanner
ors] fy2 ae
Here
Dis= tails
pps Whew sun of subset J is + then omly we have
i the given clp .
= fe. Si- $2 = af
ee
a count 2
Fm
os
we have tr Cout
So we Nave “reduced this Ceust-
CUCUUT TT
# cout of Subsets os GrudGut of
with given aiff - Subs ethiun
E,
J,
tt
int sume = off + Sum(arr)
2
rretum cous of Subset Sum (ore, Sum)
ink countopSubset Cun (iukLJ arr, iut uu)
[Suit alization
I Fraversin
if (amd <=)
Wag) = th-agI +t O-ILj- eb
Aye
461g) = t0-9G)
rete Cn] ous] 5
GULLUCTUUUCTTTT
Scanned with CamScanner+/-
allowed
like we can take ay of “the sign to any chavo
EX
i pv -a 43 |—> sume!
Ho ott +2 -3 | — Ssum=!l 3
(WW -2 43 | — sume]
+) + reo
Css
(sam) — (sum)
4-3
zal
Tin in some an Hu tout of Subset sum diff .
Scanned with CamScanner
eT TTT N ICN hee tele te teteteange© Related problems »
© Red cutting
© G@in change -1
@ Gin change -11
® Maximum Ribbon ut
VUVUTT OTe
2 Sh unbounded Knopsack, multiple occurrences of item is allowed.
2 Jn oli Knopsack, If we include | exclude the item, thew it
is Considered ao processed item. Means, we Can't consi dew
im ie “danetion .
2 dn unbounded Knopsack , we Can consider a single item rmutipte |
items .
2 &.
det's Sup pose I like Ice-c7veam,then I can take Ice-crtom
multiple times 7
and
If 1 don't wat burgev, then I'll not consider it leven
Gf it has been Offered fo me multiple time
‘ULEELELCELOELOESG ouy
7
Scanned with CamScannerEE —————
In ol) knapsack Spath processed v~
(Ease
“Hem Exebids processed 7
In unbound
ee Rnopie Telus — IN Process
Exelud—+ processed
a eel dors
G@de Variation »
Bt Variation :
of. knapsack cock >
ea fect ae
Jo[elofolele |
Cel T |
f(oG-J -D
+009 = max (vat + t(-]G- wtli-], 6-053):
Slolo
che
t0IG) = 0-IGI
Jn thio, if we considey the ekument theu we odd the
value of, that ekmeut and we move forward 1.2,(n-1) 7
but in unbounded Kuapsack 5 we can take the eluent 5
mattiple times So we dont have to (n-/) >
yariofier prise] dengt o nd
Sometimes the Leng th to nat que a the question thn
we have to rake the tangth only | by pusking + to
elemends in the length anay
us sw
prelj— wil]
danght} 9 wet]
Howe , we com cut rd dhe in came i Libe
33,2
Lit, 6 8 unbounded _
a bepack
Variation
Scanned with CamScanner
ZZ 2 ILL DIO LO OOO er erenenenanai!Code
if(length (-<= D4
dp (JG = ome G+ api G- Lyte) ;
ap (i-IGI
else f
alJG= op IEG]
}
PE VECLEEEELELELELECECEECCELELODY
Scanned with CamScannercoinC])= [1 [a F ins id thet,
anaes 13 Infinite Supply of coins
243<5
24241 =
[Fl+3=5 ; mt
(F1 414225
(t)t+64it) oS
Now we fave to cout the rw. of ways du whiel
we Can obtain the given sum
> oop p rin,
bat bape, ‘tao anroys (oat § vot) were jinn Hun
whenever an array io ica Thin conside, 6 ao wt ae
MATCHING
coins[] ——> wt lJ
Sum —— > W
— Tio io unbounded fenapsack Cawe vrepetation is atlowed,
ea TPL ITI OI ION IN eteetreang,
Scanned with CamScannerSubset Guy
Tn question is related to SubsetSumt pre :
uf (an[i-J <=j) |
eOIGI= *G-OGI I (0-0-6);
ele
tiJGI= tG-9GI;
Couk of Subset Sunn
farli-J Hence minimum 2 colhs
wooing 4E— WHET 2 = & ave requuredl,
# cainge3 E43 = oT
Hoinse 3 e—— 22H
ap[dins sivec) + ][sum +r]
e(4J[J
——> Sm
e7 2 3 4+ s
, 1_»([Link] -4)
! lo { TWIST
oO
iS Hum
sUel\
w S Goinl] i $ F SO We Tart make
0 Sum=1 thio situation
ASigp means coins array is
oe So we require wifi, wate
ine which Cums up fo
@ Sum voli
but we can't take imap hy in that
So chore [Link] -
rly od 2
let's fale atter ti,
—_—_——
Scanned with CamScanner
FARA a AAT ATEN GREE Eo 88CLGULUCUUUUEE OEY
{,
\, U \ L L L b CLEULECEEEG!
es 12 8 4 5 6
°
i
2
3
orscrd
Sum=3
> no. of mia coins
Ouest eee
° INILM#y J
4 |
2{° q
if ow=[3Ts T2]
far-(3]sTa
but dength=1 Sum=4 ao
Bl win. no. ef coins of clunomination “3
4 23,284 ain Such that we get Sum = q
yun =.
ape CNoT PosstBLE)
© (int-r1ax-1)
Scanned with CamScanner# (i ,anG}~-— por
f (5 Xar[i] J20) put INT-MAX-!
for (int jel 5 yb
Longest repeating subsequence
Length of longest ee cf ‘a’ which is ayn
Subsequen ce Pattern Matching
Court how many times (2) appear as Subsequence in) ,
Longest podind romle Subsequence .
Longest priindromic Substring
Count of palindromic substring
Minimum no. of deletions in a string to make it a
indrome _
Minimum no. % Insertions ina string to make it a me
palin drome.
_
>
EE zB
Scanned with CamScanner
@ ©OOG G8 goeeeet
TETTTT ETT
tl
erert
TOLL
vt
4
AV
oars
Se
bd Longest Common Subse quence e
Recut
We i
“Two strings will be given
string %= “abedgh” size(n)= 6
shring Y= “abedfh1” size(m) = 7
xe c@3® — abdh
esalshony, 86: @KRO.— abdh
Subsequence = abdh
ian a4
sumer’ 3, sie
© Base Condition
@ Choice Diagram
+# Base Gneddition :- 5
i th str is Zero
if the length ef bo ing
if(n==0 I] m==0)
vetumn 0;
pasa at syorits,
“ep,
sy bn
Ak ede ay
aNd vd sD sy taggly,
sation ante on
vant
wie
tet
Scanned with CamScannerLL ————
=—__—
Choice Diagram
(l-d == ylns]) 2 if the Jat chert.
matches
— Matches
——s Cs
at. | ree — if not matehes
int m ,int m)§
if (n= Here, we will chek
\, whether fio ion is
alrensty calle! or not
fs
How To CHECK?
———— _
Check whether the value is
greseut in the table or not.
Scanned with CamScannerVULULLELULELECOCOLCOCUCUUVULC CE EES
4 globally declaration of the table
Static int dp [eoi)fooi] ;
int Lcs (string x, String yg, int nm, int m) $
iF Cpl Gn $= 1) Ff
} return defn im];
#COB-T== y[m 5
dp[n][m]= 1+ Lcs(xsy,n4,m-);
3
elses
dp{n][m] = max (“a /n,m-t) ‘ /
Les (x,y, n-1,m) ]”
5
veturn Ap(a][m];
Scanned with CamScannerIEEE" J TET
=
© Bottom-Up @
ee
base conclition Initialization in
In veeursion otto -up
if(m==0 Il n==0) — ze Iuitialne
mre] Te ae
°
°
x:abef — m4
yi abcd of 4 neg
ap(sI[T] —> dp [msi]fn +]
— > 2 Cy lengino)
m Th
Catengtho) He auner
[[Snitializati on
dp [m+n +i) 5
for(int i=0 5 Tema) + i++)
for (int jeo 5 EMH 5 hap)
if (i=l 2)
opGiJGI = 0:
Scanned with CamScanner
a]
ct
oF
oF
oF
F
i
ar
Z
:VUUV CUE E EEE
TOU
CUTIVE CCE OGG
I
for(int i=1 3 igmar; 14+) § ip
for(int j=! 3 yent yen
if (x@-J== 9G-D5
dpfilj] = 1+ dpl-G-]
5
else F
GIGI = mox ap fiIG-4,\
op lO eo)
t
j
seturn dp[in][n]s
Scanned with CamScannerL VI
“Two Shings are given:
Si = “abcde”
S2= “abfce”
Jn sub can be qound by spring
sapiens thier, Heroe he Shiny
Py » SEI g
x si = “abe@e TS 'obce 5 abco
Si: ~ ab ce" — abce =—
skipped
But in Sub siting > & answer should be continuo cu.
si = “[ablee—— ¢ es ave the
; ab
Sas (ORES
Saectings
I Initialization
Lo <___
t
Lil
for(int jo 5 Temas i+
for (int j-03 jemsis j44)
if(izs0 Wy==0)
PLiIG3=0
I Main code
for(int i=l 5 idmer s itt) ¢
for(int j=! PSM 3 f44)5
iF Cs\GG-J == saG-D)§
ea de -TG +1
lve
‘ UpCICA <0:
3
3
Tea TH ya ap AA KID
Scanned with CamScannerEE ZOE IOS OUECLODULUOEDEEBETCEECECECEUYWVEDODS
Q
°
|
shing S1= “acbef"*
String Sa “abedof":
my 3
Longest Common Subsequence = abef
“Task is to print the Les of tv0 stings.
How actly us works 2
s)= “acbef" —om=5
S2= “abcdaf"—9n. ¢
dp[m+i] [nti]
9G Fab —GhC
Pre RO 12,
$ efofo olo|e lo Guike this shing is
fa. oPAT | lites there
2fo fr 2] 2] 2/2
63/0] 1 eee 2}2|2 Tron,
ct fo] i fofafa] 3/3 :
fSloli1 jz {3/313 (AL
a Je-= SoG a==q
(sre 45) At iz0, feo SLI = = Se" aptag9 = epC-I0-0
At i20,j21 Sil] f= GJ
S» dpGij GI = dp (1-957,
dpfij GJ = max, op 6G-0
Scanned with CamScannergame
RE sy We will go
Now a $c cliagon.
“fcba ” are not equal “9 oa
go gind max (3,2)
and move to thet
cel, 3 is max
. a Sd move Left
bef This pres we have to
Te out answer polo
jo 4
an Equot (ij)
if Not Equal (i,j)
Reverse c)
Vad ddaddda Ao goooas
Scanned with CamScannerGOLD
ote Me GF EET S°USOLEODLEDEELEETCTUUUTLSG
© Prepare a table for LCs
® Now we have tw start from the [at cele
while Cir && J29}
f(silt-J == s2G-DE
ans += Si[i-Ji
i~e:
J
else f
if (opGiIG-1 > ee G-IGVI
jt J
else .
j
creverse([Link]) 5 [Link]) ;
eturn ans;
Scanned with CamScannergonecreeseee
Shing q: “geek”
String b* ~ eke”
—
merge
Merge them in such a way that
geelce | both a feet? are
Thus is te Shortest feng He
a~ *AgGTAs"
b “@xtyaye" FR
( AGGARS GXTXAYB
[HaeaRETTE | spercopenn
Find the shortest Supersequence(Jenath)
a."AQGTAB"
be “GXTXAYB”
A s
GST AV, GGTAR } present
Gerke S preeent
This is the shortest Supersequence
dength = 4
tt
Scanned with CamScanner
POPPIN NNLLNIDILI IIL IL LY WW ewe resent eeela. A AB BG at thee a th
bs TX AYB pay _ “ falrea
q A T Ly Write one |
AGGXTXAYB u
Longest Common Subsequence §@)
Wheat would be the worst case af taking Supersequence
8
6
Q: AGGTag
b: GxTxAyg
wal \ 2,
Raarad + QxTKAYE
Us= "aTAB" yes =*GTAN™
t
IDEA
length of Shore
Supersequence
=mMtn
Ls
Shortest length of
eel uence.
Scanned with CamScanner
LUGCUGCCCCCOUTUCCTCUUT TTT TTYint Ucs(shing a. shig by int m, int 9) §
int dp fms] [n4q;
for(int ito, i¢ mets itt) §
RrCink j20 5 jemte, 544) 5
F(i==0) pli <0,
if (j-=0) apliIQ3 =o:
j
for(int jet + jemey vite) {
Tor(int JEU Gann js
if(aff-i] == 6)-7) §
oC] = + aphi-dg-9 ;
else
deG] Gj] = max ae IE}, dp Ci-JG7);
; ( 2)
5
t
teturn dp (mJ Cr),
j
jot mainc) 5
string a,b;
cine? aprb;
[Link]) + b-lengthG) - Les (a,b,[Link]),
cout K alength ‘j mee oa
] J
Scanned with CamScanner
Dy af iio hii i hla
Vad adalahTnput -- Output
a: “heap” Tnsertion: |
b:* peo" Deletion. 2.
convert
iy
Vth
a—m"s
heap pea
“Low Hh if we Should aft Les or not 2
“TWo strings are given 4 optimal amwer is required
then it is a vaniation of Les problem .
pea Remove la Pp ee .
Grsevtim) (deletion) map ea” yemain untouched
—————
——_
w @
WHAT IS “@a"? |
q convent, |
Ce NEE
We will do nak usp diye
ex Ree mM Convers "
a)
way! insertim in‘ea’ to
> om ‘a‘ ae Convert to‘b’
Convert to a
en
:
UT
Scanned with CamScannerLes (shring a, string b. int ms int n)5
dp[m+iJ [n+];
MI Tratiatszation fr
Ht yaoi cody
(luk ists igmans itt) §
for(int jor 5 Jon 5 jas
else §
3
}
netune dem] (0) ;
3
mo () f
Mbput aif b tos
Gut <.“ Beteton Min. delehow " ¢¢ Q-lenginc)- Les (ab,m By)
cout <* Min. Insertion “<< [Link]) -Lcs(a,b
«5
fonte Seevaen ct berxiyesy otirecal > sottelel [o .c0 muta
FCaC-T == BED f dp Ci fjd = 1+ pO Gi
| PUIG] = me Cap (AG), a CI),
10) end
LybWauudaIAIAsdaddad,
Scanned with CamScanner)
by
DVTTTTTTEY
iy
y
L
VUUTTT TTT aay
CEE ES ee ee
One strin is ai '
jiven , have to vetutn the longest indromic
Subseque g yeu aw urn the long pout
St*agbcha* ____s TH fla,“ abcha"
ofp = Thi is Longest palindromic
aaa! find all subsequences of hing “s" Subsequence .
— then find out » How many subsequences are palindrome
— veturn the max. length all polindvomic Seen:
SG 7
all Patinarons ;—— Longest length
Siubsequen ce [Stbsequences | .
Mat i) Algovitla. =
Up g dp
we com thik of like fio another shing *b Xs
a qunsion of a string
Go LCS aw ery
a. a
b— furca)
Scanned with CamScannerString as “abe agbc ba"
— lets reverse fio and store it i7 b
9 ="646© 66"
b= “@GHOOg@"
oo a wf ah
“abcba” ——> Tho is US
AND GUESS WHATT 22?
TRIs IS ODR ANSWER
“abeba” | The is longest patindronie
[‘abeba” | Saleuboe
lcs Ca.b. m,n) §
Code
4 sailliropiA pinubinii
I) Les coc.
J
maind §
Wuputa” 3
6 ein SL
orevore (stv) begin d+ [Link]};
best;
abut & LES (arb,min) end;
5
Scanned with CamScannera
TTT
beb abche
ea (# elie 21)
indromic
Pgunsequene CF deletion =5)
ps
ink Pd
ry
As we ave deleting the maximum chavacten, We
ave getting shortest palindromic Swbsequence ,
Hence,
Length of patindramic 4 i
quence Number 2 deleHove
Simp!
BAAR BRN nnA dl!
length ot
— Find thellongest palindyomic Subsequence .
> etn (Length sf Shing) -(Lergh o longest palinevonne
quence
Scanned with CamScanner, ncvhaite a al
PF
Ip: a: “achef" aS
b> “abcdaf" op
ofp: “ ackedaf" Pf
_ or
=> dength of Shortest Gramon SeperSequence =f >
eee we have 1 print the length et (scs)
Now we have to peat the sting.
6 a bc da : a
ff-e[e[ o] o] of] of o 5
afolrjr|s bopaeka
Clo ! \ 2. 2] 2.
bf > t}2{ ef ata
clo [i |] 3 [Gy <
fie Tr]}2,at 2 ‘
Match ¥
Hereagcae f
MC rual hun ce
move f> max (4p 0-45), ep GIG-)
bulk add the chavacey ct lower cel)
Heres Mter faking «¢' jt will move to ealt MS
Atter ~y I jet |
| but befure rnoving add the chavocter f ana and
| en Lets code Huo portim =i
—_
Scanned with CamScannerCUIVVYVVI ITT TAY
i
UD
J
v1
mn
Jd
ALUCGEOUL
v
t
Shing ans = i i= mlengh0;
While( iro $4 jro) § ut = bs Length):
iF(a(i-] == bG-)) f
ans pusb- back (afi -)s
else §
if(dpGe]G-J > dpCi-JGI) §
ans. [Link](b[j-!));
yO
else if CaplilG) 1 < 4pCi-1GD) §
ans push- back (a Ci-9 \3
5
dn LES we are talking about we aan stop our iteration .
s ae 44
tcl have topped her |
|
: 6 ead 4) "sti
How awe Tt wou rot mnandako
GS that it Should reach
i iptin
oo c cell (018) in prin 4
cs
ore HH L tL |
Let's take an example |
a: “ac" |
Tf we stop here, means 20) bw |
then we hove td add +the Then us =
remain Oh! chin but in sce = “ac! |
Cawe in SCs we take aggregeln
SO
Scanned with CamScannerwhile ( i>0) £
ans push back (a(i J);
Lmportant
while (j>o) §
ans. push_back (b(j-J);
| Final Coee
© prepare a table for LCS
© Now we have to Start from Lost cell
°
© string ans=*";
while (iro $$ jro)§
f(afi-] == bG-d)§
ans push-back(a (i-1)+
j= =3
Jr
j
else. “move left
iF (4pIG-J >dp G-IGD§
ans. push -back (blj-J)
Jj--
i
else if (Ap HIG-AS ep li-IG Is
ans push -back(a[i-i) >
ery
Wedel e ed ddaldddud ddda de
Scanned with CamScannerPObGDHOOD’
while Ci iro) f f stem
3
fe
ans S push - back (a i- Ds
while Cj>0) {
j
ee
ans. push. back (6G-Ds
Jo-5
Scanned with CamScannerShing S =" AABERCDD
__-rordier (should be maintain )
> discontinows (/)
let's take a Subsequence = “ABD”
WE ec OH
CS Suna
ABD “ABD” occuvs = 2 Hmes
Subsequence
gn
“Ac” —5 2 times
Arswer 1 “ABD”
ant the
me lengthis 3,
Output the length of longest Repeating Subse quence
Given Shing is
a Aeee ee
on . tind Les
S:“AABEBC DD; Thio will never
i ©
AA on in longest Re a
Suby
i -. 2 eq ene,
AABBDD
“SN Our Arve)
Aap
Ago
(AGA GA RAG a Ga Lan babA Sis ila ad.)
Scanned with CamScannerneediot eonanns] &
Index - =
E> 3 (im both string) f catdstn’s
CS Cin buh Strings)
i we never Consider them
F Cletters come ot the same index then
= Then why Asis taken ?
[Angee DB
ARBEBCDD
‘ index
S129 AMOK) SS Tate the cross
3 A >
“Now we can take, Right 72
go ¢ es > |
att q
Now code it > a
=
We
LELLLCLUCCOCCCOUCCOCCCULLULUTUING
2D
ucs
f(aGi-J == bG-9 &f ilej)§
aeCIGI = 14 bP -OG-0;
3
els
ef -
APC WG) = may ae (iIG-0,) |
3 apli-] GI”
Scanned with CamScanner
order preserved Val
Sceseee"5
isyo" fis a Subsequence of
shing “by
) = Ay Te
So Simply we can find the len of Leg in shing afb
iF dength of LCs == leng of A return “tue
else “return — false-
But how length will decide 2
There is a possibility of getting the Les different .
a: axy (8)
> apxcry (6)
Thun ics (0 — 05% (2,6)) — length ange
[o-s] 3 Hence Jengt> will be
Sufficieut
Code
7 feeGint [[Tnitiolization
for(int 21+ icmsi + ptt) f
for(int je! FJSMAL jt) §
if (af-d == bli-)§
Ap(iIGI = 1+ p-0G)-4:
5
aed bd IIIII2
else f
opliIf I= max(4p[i-J Gf, 46IQ-d):
$
si
t = Apt;
int 4 ce etuin true;
ie (ics —— return false y
Scanned with CamScannerTop» Erancaaal fn
pe bebda
cr
(ole i. Tigi) odie a
Zinsertions { @ insertions
minimum = 2 insestions
s= *aebebda"
chang to LPS
Longest palindromic Sulbsequence.
abcha —» € 44 are removed
I
atide
Les % transform owt & fa
one ‘e’ can added
one ‘d' can added
So ewent Fi ow!
1° [p auotions = tt Jnsertions |"
min. no. of deletions
> Same code ao the
fir LLLUtb L L L t U U t 5 f COUUVU VC
Scanned with CamScannerpnileo Ho elom of pair: fo coat maith
pnoai motives,
Matsix Chain
Multiplication
© Matix chain Multiplication (Pcp) recursive
@ McM memoization
® Mcm bottom- -up
@® [Link] , s
© Evaluate expression to true / Boolean Parenthezization
© Minionum/ maximum value of expression
@ Patindromic Partitioning
® Scramble Sting
© Egg Dropping problem»
Scanned with CamScanner
T
Wa ee eed ede ef ee od sd id fed cd eh hpii
CUCUUVUUU Eee EEL ee
==
t
UTA
J
“|
J
“|
J
|
Ut
J
TUT
© string or array will be given. ;
® You will get the feeling of breaking the array [ sting olde
solving the problem.
asm
TTT ti 145
ata
Kk will move ito ¥ ene D
& > \
ay ise sock peep
os ans
(4 a j
© sun isk) an fon Cet)
© Ar of temp ane fae Sr VS qundion otter $
we will get suv ancwer.
Scanned with CamScanner|
3 format
=z
int solve(int awCI, int i, int pF
IFCiB]) —> Tig nay be diferent {yr other questions
veturn o,;
for(int kei 5 18000 + gooo
7 ?
ze Hey 2800
SS
A pst Theme wart |
Scanned with CamScannerGOLUCULCUCUTTICOTTCTTT TA
anf}= (40,20, 30, 10,30 nS
[l= {#0,20, 30,10 od
then (n-t) matrices will be given
Ay — 40x20 :
‘ 3 fap onli} « onl
Ar — 20X30 1
A3 —> 30x10
Ay —> 10X30
How fo identify 2 whether this problem is based on the
qormat given by adity a verma |
Came here we have tm put brackets
(Avs Ad),
Ai As) (As As)
Ar (2 (AsAq))
So we are putting the brackéle
Ai,(A2A3 Aq)
>t (et eye
3 Selec rhuuimaion cook
Scanned with CamScannereen a
f 1
' 3
owl] = [¢0[ 20 [ao] 0 30]
eo i
deatvix ais anr[i-i}¥ am(iJ
= an(o-i] xaw(o]
=aw(-1]#ar[oq — > (-I) index
is not vatid
Hence we con't take"; at positim o
Se we Nawe tp take i from ist
And Now cheek *j'
A> onl] * ar(jJ
3 ow[4 -] ¥ aw [4]
> aw[s] ¥ an [4] WZ Tins wreck.
$0 i=, jearrsizec)-)
Scanned with CamScanner
PIII III IIT TTI IT eee
oy? 9? 72int solve (int awCJ, int iy int 5) §
/I Base Qndition
if (i 254 ___-_, if
means “l 1. element
ast Aj=ar[i-i]*arrl iy” ome
——
Ths is invalid so
array Should be at leat of
size 2:
’ j
(Ge, Bo, 10, 89) |
4 |
vetum 03
$
40k kt ey
° aout?
orn! ye¥se
i J
( 4, DO gon. OF 30)
v :
jr k kt tej
4o%?°. EMPTY SET {
otse CG Y sf
\o
oo 39 & ck =j “)
AG © gn worst case, we can make (h-t) Partitions
nfl
4 partition
1) qi ig Jj
2) Base Condition
3) qind “FE loop
4) Apply gun(temphn);
int —Solve- sting sini; tet)
Scanned with CamScanner@ gre base condition
t (ie is (ies)
if izJj) 1 ,
. ¢ retum 0; seg covtano ont ae charade
Hence 207? pavition
hefere Ho we have fo check, after partition)
if we are getting the Pi
if (isPundrome(s, i,j) == Tue)
return 03
§ NOT
eg BLE
75
a
Scanned with CamScanner
atindromic string or not
wenn rrr aodadadagaddCUGUUUVUVUUU EEO E ED
Lae
66
LUT
Go
LG!
J
VULLLE
for(int FEI 5 Reaja i +4) {
int tempAns = Solve Cs, i) E+
Solve(S, et,
+
nea
mini = min (mini, ternpAns))
t
return. mini ;
Scanned with CamScannerI —
| seo
memoizatim—s R.c. +
nitik”
to the recursive solution, Vand j ave changing
\
I I
So
0 <11) ¢le00
dp[ooilfool};
int static dp (ioo') [iso];
int solve (stving s, int 1, int j) f
if(i<=j) vetui 0;
if Cispatindrome GS.i,5) vetum 0;
if( apGhIGI f= -19
yetuin dp(iJ 1;
for(i
int
mi
nt kei s ke=ja; k+t) §
tewpAns = Solve (s, i,k) +
Solve (S,k+1,5) +
ao
ni = min (rnini, tempAns)
5
dp (3G = mini ;
return dp (IGP
int mainO f
mer
iii i
mset (Apr “ts sizeof Cap);
int mini = INT-MAX ;
Scanned with CamScanner
Ve We eof eed ede PAST IIIIO Ase:
suit of eroiazerak; sd
2 10% ae: aloes
fwo recursive calls
See,
hoes
In the {ov ‘loop » we are calting
but ° nn check the lett part solve (& ir E)
means welll check if the let
port has the vesult then We
can Store it
else we'll call the solvefSrjrt solve (s,11 6)
“and stove the result of it in lett and
le pest Stored in dp-
Hf (4p0Tf) |= 7)
UUVUUVUCIUT TTY
oa lett = ap(i3CK;
> else
_ left = solve([Link]) ;
ml iJfel = left jo
~_ dp(iTfel = lef “Te
aa if (dpe Gj] = -10 ophini2et
— vit = op OQ);
— ele We
> tight = solve(s. Kt1,5); Gi
~_ ortvenn CSTE] = right
a = “int ter Siig 2 I+ lett
> ee Lotte | pe rght
t
CUTT TTT
Scanned with CamScannerShing S= “T or F and T ”
\ a
ss* TAF§T
i}
Shing — aa se f characters shing will be made up
Ni ate ct thee combinalions
3 symbol
']o3 “
Now toak is to dind the number of ways uch that we Can
pp insert brackets and ee" expression would be true.
sete aT
—
(T1F)47 Ti(FET)
7. a-TlF
“i =
qc 4TAF)
+
Ie ke Is moving
(TIS 15) ee
,
Scanned with CamScanner
+
cr
or
oF
or
EF
FE
oF
a
“a
“a
ot
ou
on
oy
a
oI
a
Ny
a
n
FE—
v
CUVVUUUUUUTLEL
£
D
AOC
CCET
>
{
d
VULULEUGT
OE 5 7 AF)
k
Expression _| operator Expression
FE
means, f& will always at operador
4 steps :-
© find 1 >
TIFETA EF
dl
® Base Condition
(t or F and T) xor (F)
7 \
Gr ED . EH fej
¢ Cpe’)
bt FA gk kt toy
——+ No conflict
Scanned with CamScannerexpi [ror ] exp?
No. of ways of ‘True’ 9
(test True * Right Fale + lettFabe % Right Tne
rsaadddaad.,
PIOUS dlddolel
Means we have find the ways tp -¢it ee oe
Tree on well ao Faloe-
erpt fxor J expa
J]Boe condition
iFCi>j)
vetum foe
if(i=-J)@ f
if (isTue == tne)
agum S[i] == °T';
\
eee funn s[iJ-= °F"VECLUCUCOCLUTUUCCUCT TV eevee
xo)
A \
eS) pene ep my ke
oe ate 9
{ os
keit! bej-l
fete
fpr (int Feith s Keay Ere 2)f
int leftTue < Solve (s,i» »T) :
int leftFalse = Solve(s y tet, FD)"
int vightTwue = Selve(sr etl sj. 7):
int right False = Selve(s, et!,j- FD: )
I] for ond opevaksr
if ([kJ == °$')
I] No. ef ways fr Tue
if (isTrue == Tne) 4 For Tre
ans ycdetfTrue * aight rw; ur RT
ene i +=(leffTiue # right False for Fale
right Tine # leftFalse ie «
+ Lt RT
leftFalse * vight False) > LE RE
I
eee
Scanned with CamScanner
2 Tomphr:4 fo or operatuy
else iF (std oe WS
if ( isTrue == true) f
ons += (lept True x prightFolse
+
lePtFolse * right True
a
Jett Tvue * right Prue) ;
Gedesddadae?
a
else ¢
ans += eftFalse + wight False ;
5 Rs
Oe operator $
else if (s[k] == 'n‘) §
if (is True == true) §
ans + = (lefffrue *& vrightFalse
Uh
leftFalse * aight Tru e))
5
else j
ans # = (leftTrue « TightTrue
+
left False * tight False ) ;
Be eae a mmm GGL.
Scanned with CamScanner» [ead ves}
Whenever we are creating
dimension of the table depends
variables changing in the fanctio
Tp ant
a oP. ¥A-table then the BHE
on the number of
n coll
In the recursive code
for(int keiti i keej-ts ket) f
int leffTrue = Solve(s,i, &-1, true);
int telettfalse = Solve (S,i1 le-l false) ;
int right True = Solve (S, Ett, J» true);
int vAght false = Solve (8, K+, j+ false);
MULLLOLLOLUUOVEU ELE LELY
j
4 No. of Meee a+
“ 60D or
T's Pe Changing |
chan qin' variables ave
3° (2 on changing)
Bo matrix will_be
aa
a
ae) isTrue
Jet's Sup pose constrains ave :- 0 col the function
LTTE adel lee ee el ill ee eee
Scanned with CamScannerfa
‘=
as
BS
2s
v ve veouvvvuUuUuLUULyLEeLvuyvyyyyyy
int Solve ( string s, int i, int j, bool isTrue) f
FCP >5) veturn tue;
if (==) §
if (isTrue == tre)
yetunn SJ ==°T'
else
veturn S[i] == °F‘;
$
UI New code (map)
sting temp = ‘t-string(*)
‘temp. push-back (" "); mean
temp. append (td_string(j)); ey creation
‘temp. push - back (*° “);
temp push append Costing (is Fue)),
Tey shel
if ([Link] (temp) \= mp. end())
return mp(temp] 2
int ans=o;
for (int ke itty kaj; kte2) §
int Jefffrue = solve (S, 1, k-1, true);
int leftFalse = Solve (S, 7, k-1, false);
int vightTrue = Solve( s, ket ,J, true);
int right False = Solvec 5, Ky j. false);
j
- Scanned with CamScannerNew "¢' operator
if (sj ==" €')§.
if (isfrue == true) §
ans += leftTrue * Tight Tues
sef
ans +f{(lefiTrue x igh‘ False)
+
(eft False right Tue)
i
(wiightFalce » left False);
f
5
I for ‘| . operator
eseif (S[k) =='1") §
if (isTrue == true) f
ans += (CleftTrue a Tight False)
+
(leftfalse * Tight True)
+
CleffTrue ¥ right Frue));
else §
ane ++(left False vightfalse) ;
f
Scanned with CamScanner
tye a OREN DONT MP MEN W WATE EYEee ee UT EET eee
Il For vat operator
else iG s{kJ == a)
if (isTrue == true) §
ans += ((leftTrue * ight False)
+
(leftFalse * igptTrue))
j
else {
ans += (CleftFalse % right False’)
+
(left Prue +* vightTrue)) ;
mp[temp] = ang;
veturn mp(temp] ;
sw) OMiqqn az st} of
gl-nor to anbore lore >
Scanned with CamScanner
\
—a
cejasmoini’ onsldoxd 42 acm
” [Semis]
Given two Strings ‘a and ~b’ , ¢ér check wopaitor “Hey See
Scrambled string or not.
Tips a:~qreat” ofp = Fue
“What is serembled shing 2 cs
© Groh o binaey tree.
® You cannot make child of binary tree emphy
great
KON — Not allowed
great *
|_, So these are
Scrambled sting
You can break down in ony or
we can de the swapping (a zero or more) times of the
child web rodeo ca non-leaf nodes
PPE LOLLLL LUE eeddddddddded.,
Scanned with CamScanner%
ie great
u
x
g
gre at each leng
Not allowed
A ppro ach +
LUUUULULULUUUYVYUUUUUL EL
Scanned with CamScannera—>b a(fint) b (fist)
a(last) — b(srst a(Jast) — b (Jost)
io “et orn sy bso] Salve Carb)
a
7 V eaigr
if (Solve ([Link](0,i)_, [Link] (n-i
agar 44 Fre
(or a ‘
solve ([Link](i,n-i) , bSubsh(o, i)
224 3 -_..
Tree
S
cose geet gheat
Fok he
if (solve(a-substy (oii), [Link] (0,1) =e true
S) solve ( a. Subst (,n-i) i heuer Tin-i) == fue ,
et Pees Inoyp tqoua
ot z
os ¥ hos P tose
Scanned with CamScanner
DLAI TT I le el el el le eed aRPYLULLUULEUUL U t t COCUCVV VV Vv
if (condition 1 == true | cmnettior -T ++ fe)
yotum True
UW Buse Gndition
great orgreat g i (eat
« 6
f(a § b ave omply)—>-vetumn 1M! oe
if (a. compare (6) == 2) ae eae ia 7 ia
Caz! 7
if (a-lengho <=
ttun false;
Final Gde
int maing) §
sting arb;
cin >> a7> b;
> if [Link]() {= blength) —> vw fue?
> Both emphy ——a “return fose
— &qucl — ardum Trae
Solve (ab);
Scanned with CamScannerbool Selve (string a, sting b) §
if (%Comparre (6) == a) reum tun:
if ( a. length ¢=1) refum false;
int n= [Link]
bool Prag = false;
for (int d= 1 5 Ten-1 3 itt) §
if (conditionl {condition IL) £
flags tree}
break;
J
}
vetum flag ;
3
Scanned with CamScanner
ee ee i ee ee ee oe oe oe oe eeTTT Tae e Tee ea Ty.
Ct
ae
>
te
Fa
f passe ees
[Sconbied sting meniced} E rsidevt eaiecord 63
Mee vate { te
Uy present
Before ———> cheek maf a —
Colewlat.
Atter ——» Stove value in map
bool Solve (sing a, stting b) 4
if (a-Compare (b) == ag —
vetum true; global map ~
yit eerste ns unordered -map string sky op
}
Changing variables —— 4 45
key > sing = Safecpe) oPs4 be
string key = aj a a"
key push back Cy a'a"
key. append(6); = 27 @_b”
iF(mp find (key) Je [Link]()) §
return mpl toy]
int n= a-lengihog
bool Aog= aie:
for(int iets ie sitt) f
if (condition II conditionI1){
flag =frue:
i break;
Gi
3
vem vs eeil = 9)
J iat stentless tamil
Scanned with CamScannermem pater
Gen no, of eggs ‘e' and number of floors ‘fi
->| olp =3
5 ae
=
* gail break
2 spedcthe critical floor such that ©99
tt
Butsing J | asbek
i Egg will ast breols
Fl
cl
waseiiarave fam top th bettore
then we have to find the minimum rusubor of attente
‘enuined tb identify the critical floor,
[oie awe Bese Tees very See J ie TN tongs &
O00 5 minimum no. of og
cece
attempts
wisely
eas, Best Technique, Stretegy
S® we con start rem botom ftoor
\ cawe & even if we dp the eg from bultom
it will not break ahd we can we that,
e949 again.
OOOO OOo LULU Wekoddddddddd.
Scanned with CamScannerJULULLELLLELUULCECCUCUUUUUUUUUe ee
Th ec)
and ~f! floors are giver
then in worst case. ee regime
e=3
+o
we \S 60 we require 3 attemph in worst qu cane.
e
Now the main quition ]s —> qr
2B
from here alse
—— Vag vil
Here, egg vill break, means
sg i- we'll check for thae floor
preaked|
GD 695 Cha> reduced by 4)
19} avlod
zo a shigg =<
ane
. d find FS
[3 eprsenis the array 1) Base Condition
[s| um) & loop
Ae lv) ang e— tenp
Sl ef ee ons
P| k
[et
m where we can Start out
dropping exercise
23 means’ gird thee & loop
— & xe TH loop ary ear]
foxr(k=I A ecy ea)
Scanned with CamScanner[[Base Condition
fink of the amallet valid Jopet
e a if (e==0) we never tied om
aor if(ecei) Seton Ff
‘if(eeet) ONY
fo olt Soon! cooe WH last ror
ae anor Garr |
(f2-) mew fi =|
CfecsomteF; pe ‘thresheld te will
— Tenphns Solve Ce, f
ooy ee
Break emacs
solve (e-1, E-)
4
k
J
Suppue f=20 pe reek ae OF Bry
So meas 19,12 F beeak olf
ONT
and Hin \s pr Sure
and set BF gist floor aR we fi ae
eg break “87 sve
So a) az star Rar
Scanned with CamScanner
— [solve (e, f-e)
le 1)
cI
ror any EDT TERROR AACR.~~ VEVVUUvvUvVUELETLULGULUULUYUYUYYUVUUYU UY
|
Int Solve (int e, int FY fr
4 Base Gnditin .
if (f=r0 1) fe=!) eho fi
if (e==! >) 7etum fi
[ask |
minimur 10. of atfemp ls
in worst Core
Wk loop
int mn = INT-MAX;
for(int Eel > Reef; RAN Sf
ine temp = (Dt max Solve (er e-+),\
Solve Ce, f-b) :
ach [terior one! wi jaye)"
we om / 7 (awe we have to find in
atte wont cant |
Mn =_min(mn, temp); Don't
get
$ Minimum no. ef attempts .\ Confused +)
teturn mn;
Scanned with CamScannermatrix dimewion? nunber of Charging ryariable .
Cn
\
\
exf
% e@ aud + ave drag
MN gpbat declaration o table
int ctadce =4le Je]
int Solve (int e, int f, int dpCICDs
EC fe20 Ue fea) retum f;
f (eet) vetum f;
“A (éple(e] (= 4
vetum dpe J [FI
jut mn= INT-MAX;
for(int k=l i Keef i ett) ys
int temp= | + 0 ey. ;
Solve (e.f-e) J’
mn = min (mn, temp),
J
retum dpe] [f] =n
f
GG a al al aa i Oo al a
Scanned with CamScanner[optimization :- = af thio subbree is not Solved
Solve (e, F)
==>
Save (on me
Then we wore aesuntd thot Tihese oth subbrees a7
not solved.
BUT
Thin io nat necessarily ne
Tt can happen thet
one of them hos been solved.
| As it is (Copper cote)
iF (aple-d [e-) !=-1)
int low =dp[e-i) [e-4:
else
& low = Solve(er!l,k-;
dp [e-(Ifet] = 10;
if Cdpfeltp-) = - F
int high = dp (eJ[f-I€)*
t
Jee Sa solve le, £-k)i
Splel [f-¥J = highs
\ut = [+ max (oe igh) i
mn = min (mn, terp); a
3
> vetum dp(e] [f]= mm;
Scanned with CamScanner
AVUUUVUUUT TTI UU TUT drrererrer rir
AF