Docsity

Dynamic Programming (DP) Master Handbook | Complete DP Notes for Competitive Programming, Summaries of Data Structures and Algorithms

Partial preview of the text

Download Dynamic Programming (DP) Master Handbook | Complete DP Notes for Competitive Programming and more Summaries Data Structures and Algorithms in PDF only on Docsity!

KEY CONCEPT Dynamic Programming (DP) is an optimization technique that solves problems by storing answers to repeated subproblems instead of solving them again and again. Tn one sentence: “Never solve the same subproblem twice.” WHY DO WE NEED DP? Example: Compute Fibonacci (40) Mest beginners. write this recursion: Looks Negant... int fib(int n){ F : <—: But it does if(n 5 times | | Every duplicate | is wasted \ computation ! TWo PILLARS OF DP 7] @ oveRLAPPing sueprosems | Fxample: ‘The same smoller problem is FEKE? solved multiple times fib(4) + fib(3) @ OPTIMAL SUBSTRUCTURE The optimal answer can be built Both smaller using optimal answers of smaller orguers combing subproblems. to form the larger —- answer. * WHAT IS DYNAMIC PROGRAMMING ? — THE FIBONACCI GATEWAY MENTAL MODEL Instead of esking "What is fib(S)?” multiple times, ask it only once. Store. it. Whenever needed, reuse it. Like a calculator history. DP SOLUTION IDEA Reuse —> | Store [>| Whenever Answer Needed Now every’ Fibonacci number is computed exactly ONCE. DRY RUN: Compute fib(5) ig ftom DP Table Fib(o)=0, Fila) = 1 i o;4 2,3 /475 ‘Step 2: fib(2) fib(a)+ fib(o) = 1 alt] =4 a}) O} 1) 4) 2)3)5 Step 3: fib(3) =fib(2)-+ fib(a) « 2 ap(3] = 2 | Step 2 fibfs) = AE(3) + B2) = 3 ipa] «3 What Happened? : V Each sfite computed once. [| Step 5: fib(S) = fib(a) + fib(3} = 5 Vv pall future ‘al apl5]* 5 vf No repeats. Vi Time reduced from exponential to linear! | C4417 CODE (BOTTOM-uP DP) #include using namespace std; || class Solution { public: int fib(int nd { if (m <= 1) return nj # Base cases vectoréint> dp(n + 1); dpfo] = 0; Hf fib(o) = o dpla} = 1; Af fib(a) = 2 for (int d= 2; i cm np i++) {if Build from smaller states dp[i] = dp(i - 1) + dp(i - 2); ,retern p(n]; UP Answer ys | WHEN DP CANNOT BE USED - ir arses es COMPLEXITY ANALYSIS | Sere, prely fates ai ie aan, Li iatnal el oe ae | Example: Binary’ Search, Merge Sort, Heap Sort Pome Becarsiom | O(2") | On) | Exponential calls (use recursion but NOT DP) Memoization O(n) Oln) | Top-Down DP . MEMORY TRICK Tabulation Ota) | Oln) | Bottom-Up DP @: 3/8 RULE: Space Optimized | O(n) OC1) | Keep last two states only RECURSION —> REPETITION -> REMEMBER (DP) E “Tf rection repent, UP competes.” rye) COMMON MISTAKES ZY | summary PRacTice PRoBLEMS @f ry ‘COMPETITIVE Pan INSIGHT Wg ans X Thinking every recursive Tie problem ic DP. pareve ites it X Using DP without overlapping + Same state visited repeatedly subproblems. | + State can be represented by few variables | => DP is often the right choice! \ X Forgetting base cases X Rasemputing solved states. |] |X Sumping to tabulation without || )|__saderstanding recursion.) + DP stores aniwers of subproblems, + Based on 2 key properties: LeetCode 70 - Climbing Stairs LeetGede 166 - Min Cott Climbing Stairs 1) Subpeablems ER es + Fibonacci shows shy DP ix LestGsde S08 ~ Fibemacei Number * 2) Optimal Substructure, Leettede 118 - Howse Rebber bial ia | LeetGede TH - Delete and Bar, Compute once, reuse many times, | MA took | in Chane Reduces exponential to linear Hime, coy, 92 Eat Distance [ve is nat about memorizing formulas, I's about THINKING in term of STATES and TRANSITIONS. | MEMOIZATION (Top-Down DP) + Recursion + Cache = Smart Recursion # What is Memoization? f | Intuition - Why Memoization Works? / It is a Top-Down approach in DP where we Recursion Tree fer fib(5) jE ee ee use recursion + a cache (dp { mop) to t store already computed ‘aus H © fib(2) > ans ly © fib(1) computed gnce QE When to Use? a |¥ Problem naturally fits in recursion. Vv State space is large (not easy to iterate). ¥ Many overlapping subproblems. [° See? Same subproblems are solved multiple times in recursion. Memoization eliminates this ition! = C++#17 Code - Memoization (Top-Down) Sey { Step- by-Step Dry Run: a) { o1 | #include _Galll Stack (Order) Action 2 | using namespace stdi @ fs) és lates 04 | class Solution { . 05 | public @® fit) Go deeper... 06 vector dp; ® fib(3) Gad 7 o7 long long fib(int n) { 4 | long Long / 08 if (n <= 1) return n; Hf Base cose ® fib(2) Base case -» 1 og AF (apn != ~1) return pln); 7 Already computed | @) fib(1) ficult ath ch a #f Recurrence + Memoization ; 7 return dp{n] = fib(n - 1) + fib(n - 2); ©) return 4 fib(2)=1 sll @)| return 2 fib(3)= 2 | long Long fibMemo(int n) { . # | dp.assign(n + 4,-1); / Initialize all as -1 @| return 3 | fib(4)= 3 A return fib(n); Hf Start recursion | return 5 fib(5)=5 uly, t ! Small Example: fib(4) with Memoization | < How Memoization Solves It? > Sf ——— ee 1 Fib(4) fib(3) fib(2) fib(2) Without Memoization | | | With Memoization | ? 2 1 1 X Same states reeomputed. ; . % Exponential time. x Huge recursion tree_ 1. W Each state computed once. eto y (from cache}} wf Results stored in dp[). | J \ @ | Result: fib(4) = fib(3) + fib(2) = 2 +4 -/3% a = = = (—~ Key Points to Remember & = ‘| Common Template (Change According to Problem) | — f @ Memoization = Recursion + Caching # dp(state] = answer for this state | T solve (state) { | @ Use on array (ap) or map te store answers. i (eat cas) Felhn keea + Base Case © TF dplstate] already exists > return it = if (dp[state] != NOT.VISITED) return dp[state]; | Already computed? @ Reduces time from exponential -» polynomial. 'L T ans = ...; MW Transition > Compute. hihi erinanieiainat return dp[state] = ans; // Store & return + Store & Return Lo } ( Wien ie | Time & Space Complexity © Common Mistakes 3) | Real-Life Analogy Practice Problems | a Let_N be the munber of states. 2 Fergeting to ince dp | Trae Ys ae trwveling aay: W Large state space: Time: | O(N) with -1 (or INF). | and atking for dirctions | + LentCede 509 - Fibonacci _ ¥ Hard te iterate (Each state soled ance) ee |e ete i] = LeetCode 70 = Climbing Stairs (o# Natural recursive | Space: O(N) frem dp. Cm ? Medium: tk structure L (ap srray + recrsicn stack) | 2% Wrong base case eee + LeetCode 198 - House Robber | Sparse states ee oe &M Infinite recursion due to ees — ee (ike trees, graphs) » 2D, = _ L (oy or even more complex | oe ry foetal + LeetCode 72 Edit Distance | recursion with memory!” QD “SPE "Memoization is not magic. It's just STATE DEFINITION - The Most Important Step in DP What does dpLi] or apliJCj] actually mean? * | WHAT IS A STATE? A state represents a unique situation in the problem | that fully captures the information needled to solve 1) Fibonacci (fib(n)) What do we need to know? EXAMPLES OF STATE DEFINITION | 2) Longest Common Subsequance (LCS) 3) O/4 Kropasck | What do we need to know? | What do we need to knew? the problem from that point. Only n (the position), Two indices i and j | Current Hem index and | (prefin Lengths of strings). | current capacity. Think: What do T need to know | | us eet te EAL Bit ‘State: defn] ‘State: dpfil(j] State: dpi [w] he eat 2 Masking: Fibonscel auwber Maaning: Max value using first i ati at position ni. J | |i tema with capacity w. NT i " 7 INTUITION ‘hosisdisas | Wisualisation Your state should be a complete summary of | Capatity (ul) the problem up to that point. | a 12 3 4 5 Tf two situations leak the same for the future, HODDO® | of thay should be the same state, i se Example: Tn Fibonacci, only “na” matters. dpCS] depends on 2 pC DC) In LCS, both indices “i" and “j" matter. pA] and dpl3] ; 5 | Each cell is a unique state, HOW TO DEFINE A STATE? STATE DESIGN FRAMEWORK (@ Identify the parameters that fully describe Cc = " the situation. Understand What Info Define Check State the Problem | in? |* feeraens = @ Ask: Will future decisions depend on Shah: perarmabara? Read carefully. What are the What do we need Convert that info Will tuo siuations @ Ensure no extra information is stored. | What is asked? decisions ot to know to make into pCi, dp[i]Ej], with same state @ Smaller state space = Faster DP! tach point? the best choice? dpi] [enask] ... behave the same in future? GOOD vs BAD STATE DEFINITION DRY_RUN EXAMPLE: Climbing. Sta Stairs ‘(way te reach step n) | Good State A | Bed State Stale Definition: | Explanation apt) ays | Contains only racessarg info. | Contains extra unnecessary info, | dp] = Number of ways o Bose cane (ground) L ~ | ¥ fo reach step i a i . Example: Climbing Stairs | Bad State: dpfs}PlastStep] 2 Bese case (step 2) 4 (ay You tan climb 1 or 2 sty | ClastStep = 1 or 2) ee | = Base Cases: 2 | opleD=dpttd euptoy-aed | 2 9 9 Good State: dpi] = number of x0) ® ® pL) = Gan yt ay at pul | —- | sways to reach atep i. ' 22S 2 ApLAD = Gonesngtormoch sept) |g | gl) a dp2de dp 204 | 3 “Lo | | “ tom ance ‘Transition: —_— = = = = | /@ © @ @ i eG) = aot) + de-21 4 | arateargeneaea | s | C29 dp | "3 | Extra dimension incense rom ap ik tet tag, [ a es EO | Only postion & mars! | sake space mnedlassy! ar fram step 1-2 take 2 stage) | 5 | CSD dpledeaptsese3 | 8 odo gb | re Tip . = a If I remove some data from the state, Answer = dp(S) » 8 wil affect wry fulure decisions? Abways ask | __IE NO + remove it! INTERVIEW INSIGHT ‘WHEN TO USE WHICH STATE? COMMON MISTAKES AIC. 3 sp tate ap) Interviewers love ashi 1X Not defining the state chearly. Reiner S| ra + When erly one parameter matters (position, tine, length) 3% Tnchading extra unnecessary information, | A goad state a: 1) Wha ie gow pe? + 20 State (hI) M Rigg, ona fh vip 77 2) What dows dpLiJ(j] represent? + nes tens parimatiarn matter Chee wtrings, index Be capaaity) " 2) Why i this state mcfficient? =D More Defeing a alate that does not uniquely represent | ~* Minimal * ela oS Complete: A) Can we reduce the wlele space? + Orly when albsdlhy required (use carefullgh + Bitmask State (dp mack) M Hale space i te0 large —> leads bo TLE / MLE, Lo Be J Be ready to justify your state! + Far subsets / vided states (W ¢ 20) SUMMARY SIMILAR PROBLEMS TO PRACTICE @ + Fibonacci Number (509) - 1D state 1, State definition, in tha foundation of DP. {e MEMORY TRICK ‘State = Situation | * Climbing Stairs (70) - 10 state ER 2 the necessary information. © Unique Faiths (62) - 2D chate tt i ideke aah ee a + LCS (1243) - 2D state ae 4. goed stake — clean transitions & fast cade, Par + O/1 Knapasch (426) - 2D state Ree ‘Small State + Fast + TSP (Held-Karp) ~ dpCwmask]Li] state wee Tole gee tie ars =H page st | Big Sta Dae! a wy “Golden Re Spend More Time Thinking About the State, Less Tine Writing Code! @| | WHAT IS TRANSITION? | Transition formula is an equation or rule that connects the current state with its previous | (dependent) states. Tt answers the question: IF I know the answers of smaller states, how do T compute the current state?” 1) Mesxirsine: 3) Court Wns | deGt] = dplprevt] + dplprev2] | INTUITION ot Mees | Tmnagine you are standing at step L. ——_E_T—O—TE———— d ‘You look at all possible ways to come to i ee ore from previous smaller steps. Feasibility OR plore]... You pick the best (masy/min/caunt) among That's the tran! fe 5) Tle (NA | oti) man take, nottake ) | EXAMPLE: FIBONACCI (Bottom-Up) State: dp[i] = Fibonacci number at position i Transition Formula, hg this works? is works? ‘What are possible previous states of i? Cin] + ApLi~2] | ranch, Lat step mec: be from ie or in? + From f-1 (toke 1 step) © From i-2 (take 2 steps) [ apti GENERAL TRANSITION TRANSITION FORMULA - The Heart of DP @ "* How do we move from smaller states to current state? dp[i] = max( dp{previ] + costt, dpl prev2] + cost2, wd pli] = min( dp[previ] + essti, dp[ preva] + east2, ww) “PATTERNS, ‘Tronsition tells us how to | build the answer of current ate ting ances of | previa (aaller) stale. TRANSITION FLOWCHART Pick the best uption. j . Examplas LIS, Kaapanch, Houan Robber Fick the rnin cent, Example: Edit Distance, Min Fath Sees Som all wey Example: Climbing Stairs, (Gein Change [wing Ts ik possible? Enepler Sohal Sas, ord Bras Gul deadaien DP Eaarple: 0/1 Kenpach, House Rubber | OTHER EXAMPLE TRANSITIONS Total ways = sways foam it © Climbing Stairs: dp(i] = dpCi-1] + deCi-2) # Min Path Sum (Grid) dp (iCj) » mintdpli-1)Gj], dpli-1) + grialiL) © 0/4 Keopasck: apCe]w] = maxl dpli-t D0], dpli-1)fw-wt{i}] + velfi] ) Pcl Dh age fen eR apli-2] épLi-1] os or apli] = + max dpCj] ) for oll j < i and afj) « of] DRY RUN: FIBONACCI (fib(5)) C4417 CODE (BOTTOM-UP) - Transition: dali] = dpli-1] + dpfi-2] Winclude Zz i aia , using namespace std; | | dplie2] | dpli-1] ‘Transition Applied | dpi) class Solution € Ide) 2 1 2 3 4 6 public: z if had Va) int fildint n) iz 5 = Base care 1 | #0l | ojalaf2}a =| if (n using namecpace std, class Solution { public Long Long fiblint nd { 5 || [ewe Lfeeet [om 4 ee 2) rotors H Base exes sta eacea | rtd long long prin + 0 dpli-2 t + + ¥ feng leg pds 4; Hap | for Cnt i= 2; i xe np ire) f “ elt f Update rule: Long lomg cure = previ + prev?; i dpti] deli) epli-t) apf) | Bat aired Ueki cure = prev + prevd priv, © omer} WF shaft pred = prevd | ) 7 return pravis /¥ deln] ego | ; 2D DP — 1D DP OPTIMIZATION C++17 CODE (1D DP) Evamgla: Unique Paths (Grid) Full 2D DP Table Observation 1D DP Array (Site =) iat uniquePuthstint a, Ek 5) Bs dtegd ie hil eh, i ly ba a ath G wat lang Lag? den, 1); es re te +O 1 2 3 ee ee eo eT dpCiIC = apft-t0G) + apCQy-12 peel ysee Ha ed Es EB eae ee Grd iim 44) Pek |g ea Update. root by cow: dp) on dey = 1 a gE = og 0 te tfaf2zj}ala After row 1 C4, 2, 3, 4] , tiap. ws gia Pe Ae After ew 2 — (4,3, 6, 10) 7 Lays LFF |B) Se we can keep Aer vow 2+ [4,4 10, 20] j=" see 3/1) 4) io] a ONLY ONE ROW! PF Represents current row MORE PATTERNS FOR SPACE OPTIMIZATION Pattern A: 2D te 1D (Ruw-wise) Use when: Current state depends on Pattern B: 2D to 1D (Colwmn-wise) Use when: Pattern Ci I< Praviows States Use when: = Uses old value (up) = laf alae | When NOT to Optimize? 2 When you need the whole table later (eg. for reconstructing path, printing table) Current state depends on Current state depends on same colume (up) and previout column (left. samme row (Left) and previ row (wp ehstaet last K states, Example: dpLE] depends on doCie1], dpCi-2], dpli-3] XC Whan transitions are comple snd eptimization cuits bugs. XC Whan clarity in more important than memsry, &-2-2- PRO TIPS # Wo Mways Wentify dependencies first. Vf Dray small diagrams for intuition. V Optinizn ony aPlar correct solution, Wf Use meoningfil voriable memes. Wi Test eige cases after optimization MEMORY TRICK Ty “Don't Store the History, Store Only the Memory You Mead Today!” COMMON MISTAKES a MX Deerwriting values before using them. % Wrong update order (especially in. 2D DP). XC Nek derstanding dependences caer KM Dptinising too early ithe! working solution) 2 Forgetting base cases while optimizing SIMILAR PROBLEMS TO PRACTICE INTERVIEW INSIGHT REMEMBER ® Space optimisation ‘a about storing what is necessary, nat whet is convenient. Interviewers may ask: 1) Gam you eptiniae the space? 2) What is the space complexity new? —- -- 3) Can we do it in O(1) space? Kasra et 4) How de you ensure corractnane aes far opting? SUMMARY 2 © Fikomacei Number (509) eye Unique Paths (62) * Space optimization turne big, OP + Climbing Maire (70) tt + Minimum Poth Sum (64) or salations into apace- items considered (@ to n) WP remaining capecity (0 te W) Final Answer! dpfe]CW] TRANSITION FORMULA paemh Ad UF wld] w (oom car take i) dof Tue] mand walfi-1] + dpLi-t]Le - sALi-10, dpli- 1] ) = a [Bist Ceon't take it) Move to nest ikem, Li Nu) = dpi capacity some (Wi) \_* a J a 8 DRY RUN (Example) DP Table: dp(iJCw) BACKTRACKING (To find items) Stark from dp{nJtW] = dpfJ(3] = 8 ‘weights = [2, 3, 4, 5] ‘iw ofala2]/al@#)s How te Ful? Vales = (3, 4, 5, 8] | * Row i depends an res ind [3 ot Action Bieta} 0} ao) ao] o}o Z Pay 5 Capacity W= 5 (n= 4) ¥ def IE5] «apf 3108] = Token 4] 5s eee) iteten| 0) 0) 3] 3) 3a) 3). Men e820 How to rad? | aturtecsy| 0 | OB | | | 7 | SRLSIES] = & Cem onlue o aeCSIL0] © p(2100] — Mot tohen lng tama and capacity 5) o 4q{2100] © opCaD00] Hot tab | oe ee ek) - ae aed Tham 2 (ued, wet) : SoCo) = eyCan) ~ bet oben seen} o}ols|+|s 8 | Meatwle ede ee So we con also take only Them 4 (w05, a8) Nes { ‘Wait! Table shows &. Both {Item1, Item2} and {Item4} are optimal ‘Why? Let's backtrack. (in this example, wales Tvs 8 + choose 8). 1D OPTIMIZATION (SPACE OPTIMIZED) C417 CODE : Run (40) NV O/1 Kapasch ~ 10 Space Optimized Observation: dpLiIC+) depends any on 2 ae ai Ao Hii ea ie aad dpli-Mf-]. So use one ervey dpe] Fe tae ea ising namespace thd; Velo = (3, 4, 5, 8] f int knapateh (ueckor Cink>& wl, vector& val, int W) { Capacity Wo § Update Rule (Fer Ham int n= wtsinel); “| nti: dp = 0, 0, 0, 0, 0, 0) fee OW dines to eft vectorcint> dp(W oe 1, 0); IMPORTANT TRICK inde = enpac) dere f For (int Le 0; bens dee) d For OF1 Ki heat ao ota bs ase ' pais enbipCoh (1 waverce Lasp far 0/1 Wetupeack: a awlelofelolele] | dele = wALiT] + olf) for dint w= Wi wom wifi]; we} ( dem te witli]. dplw) = max(delw), dele - wtlil] + vaifilh; Mfkae Bam 1 (eee): } Intag? Ts aveid using the sama em a ie a he ) multiple times, A awlole—s [sys] | Ielhy revarae Loop? ee Afar Bam 2 Gade: TF we ge foreard, the sane 4 item can the taken ultiple tat mata) { 0 ‘Aftar Tam 3 (sede): 2 COMPLEXITY 6 PRO TIPS AEARHESEER) behavior) w mes (unbounded. knspaach COMMON MISTAKES: vectercint> wt + (2,3,8,5); vectorcint> val = (34,58): lat Woe 5; cout <« kempSack(wt, wal, W) << endl; f/ Output: B return 0; + —Tt A MemoRY TRICK Gy INTERVIEW InsiGHT bi 20 DP (Tabte): TI Alsop waite the = 3 Therating so fram laws tu high (1D OF) ) Tetarvinwser ray aahtt fi 71 Kaopanck + Dacian 2 ial me Fe [BE Drm the DF tatde far wath cans. Fling an ae om Ga), | OF Fhe ae oo 7 2 Vath any ah tan ag was 1D DP (Optimized): et rer er a een ie Site ruthie oot ad a a EZ) Fer Veieurded Knepench —~ farwend lp, 3 Misng O/F wth Unbound Keep Fk the better one | 8) Whol oF valies are eagative? Sace 1 OUWh DD Wha ies eens a as ab ich itis, | | Onmrmmmyiating stale dateiton, ‘and move chead! | 5) Unbeunded Knapoack? WHEN TO USE? oe SIMILAR PROBLEMS SUMMARY Use O/1 Knepanch pattern shan + OA Knapeach (46) ft + Coin Change 2 (S18) a Kaapoack je the poster child of DF lhe aniichetond (9% ar not FAD : ; Fi " i ; gee: Ge sha Partition Equal Subat Sum (416) Yea + Maun Poth Summ Goud (64) frit Sinpla state + senark, tranaition we Fa pe a 7 + Target Sum (494) weer « Perfect Squares (279) we = hres apatsies ea eee + Leuk Sane igh IE (304%) fedeve + Ones and Zee (474) Yee Bowerful solution! By + Goal is max value / min esub UR In Knapsack, you don’t just carry items — You carry decisions that lead to the best value! 1. LONGEST INCREASING SUBSEQUENCE (LIS) 7s _ pp (O(n7)) Problem: Given an array, find the length of the Longest strictly increasing subsequence, Example arr = (10, 9, 2, 5, 3, 7, 101, 18] Answer = 4 (One LIS: 2, 3, 7, 101) Intuition: # For each iewlex ( fed LIS ersing at i * Extend previous smaller clamants, # Teles mason over all i @ LCS - DP Table Leb dpLij] = LES length of ALO..i-1] and BL. j-11 IF Afi-d] -- BLj-4) = dpfilij) = 1 + dpfi-a2tj-4) Else — dpCi]G) = mantdpi-290i), dpCi)Gi-17) Mower = predn] = 3) | reverse(tes begin Gh, tea ands _ return leey — — } WARIANTS & PATTERNS. - LIS Variants LCS Variants Releled Sequence DPs (atc Caper te Longest Nen-Decresuing Subsequance dr Shartast Conmen Suparsequanea (SC5) st Langu Incrmsing Subang (Cartiguma) fe us Les (Wse aer{j) = arrfi]} lal + [BI ~ Les Uae DP on consecutive 1 Tap 1 Sequence (Array) | 2 Suquances (Strings) te Number of LIS ‘Minimum Deletions to make A= B oe Edit Distance T [Count wags slang, with langth) lal - Les + lal - ucs + Insert, Delete, Replace fm ct i I A LIS Recantrestion 4 Longest Pulindrami Subsequance (LPS) Longest Repeating, Subseqwence eg) eee aad (Store parent indax) LPS(e) = LCS(s, reverse(s)) + LCS of string with iteeif ‘Type Tene ‘Olm lag ») Olm*n} sh Masters Sirs Eerentng Belerpemce | de Count of LOS Si [Tite Space| OC ar Of) |e" ar Oa (Menierinn som. rt length) {Count have mary LCS exist) * Reconstruction | Tricky (reads parent) | Enay (backtrack) DRY RUN PRACTICE Let deli] = length of LES ending at inden i Tramaition: [and + mata fer oj ¢ and arf] «fi foe op) = a Arnar s meade) = 4+ | Space Optimization (LCS) Grlg eed previous row! Use 2 rows: Reconstruct LCS: prev Start from dps] and our owe backwards Aa ad Te Afi-t) = BLi-1]) + prev ‘include character and move diagonally Else + move te direction cof larger valine. prev eure a és Heather LIS Exempla. (Otn log a} LES Example. err = (0, 8, 4, 12, 2) Acs “AGGTAR” or 1, 4, 67 . . tel B = “GXTXAYB’ {O(n ane oT a @axwtrta P - - . ro] ci alse o to ® oO;o;2 12 +} + @ + (0,8) Alo|a/a]2i2 or 3 uw 2 1jm 46 + = (0.4) @ 010/09 22 altlalalafalaa|) 22 > Gea é{olol|ojo a L 2 = (0,2,12) T Lo opo}s Max LIS = 3 (Ome LIS: 3, 10, 20) ps pot ol) ah 2 Length = 3 Biololola 2 proms |W ccomenon mastares /N\anveRvaew insicT (igh rw the DP fable Rk ie (reogae carves ee ey A EE Defi abate clnarly, 2 Wrong trenaibion 1) Can you optimise the space? Ef Think abet last decision, 56 Gk of bunds 2) Com you eacomareck Use aap? Ef Check small examples Mot understanding state 3) What's the jhaton? FF Oplimine afer you're carved. Reconstructing ronal 9) Ang altars observed? won Bee LIS & LCS = DP on Sequences Longest, Common & Beautiful! Ww LIS. = O(n lag n} (Patienee Sorting) Maintain a isk “Wail” share tailllen] = minimum possible Problem: Given tee strings, find the langth of the longest subsequence ‘ending volun ef LIS of length len present in both For each = in arr: gE + Find Uewer bond (tail, =) . ef Se ery A» “abede” Anser © size of tail Bs “ace” ar © (10,9. 2,5, 5,7, 101, 18) Answer * 3 ("ace") tah evalubien: a Intuition: 10 = (10 ? bd ce * Compare prefixes of buth strings. : = iB TE lat charactors maich -* tobe 5 = [2,5] and move diagomallis. 3 = 2H * Elea > chip eno character Fram 7 = (2.377 either stl 101 > (23,7, 102) a) 18 + (23,718) -e_B Length = 4 iH ss ng LI = Cee Code to Print LCS string printLCS (string A, (nel, 0); Foe Cink + Count ways ta farm & From Result LCS length = ‘Qne LCS = ETAB™ Mea pe while (90 BA JOOP L L)J==BLj-11) apCD Li» 2 + dpli-100)-15 else 4piD Li = mate li-1]E J]. dp lid Li- Les 2 7s WALL] =-BEj-19 € les ati i Doalse iF CapLi-4]0i) >= dele alse j=) More Praclice 4 Longesh Increasing Subsaquence + Rainn Dell Emvedaper (358) * ‘ coat © Languat String Chain (1048) > att | |e egest Comme Sebetenenee (1183) Ta 1 re |= Delete Oparnition fee Tee Strings (583) ; Spey | 7 Mies ATT Daa Se az) Te] 8) Longest Pulindrommc Subsequence (516) ir] eo + Dintinct Subsequances (115) [a] sun MEMORY reac Gy “Build From smaller, connect te bigger Ona step ok = Hime, DP makes it easier!” D Sequences may lock different, but DP finds the connection! Practice WHEN TO USE? @ 41%; Ej-1]) i-=j wee aoe * ae ae ane summary GP LTS Rind the bead, Ef Oarlapping Subproblons i enw sequence. Ef Optimal, Subtructure LCS Sede the baat Bf Sequeren # String / fray comeun etna the Ef Choices or Matching Mester them, master DP eo seers = tenes INTERVAL DP & DIGIT DP w Solve on Ranges, Comquer on Digits! 4. INTERVAL DP STATE DEFINITION EXAMPLE: BURST BALLOONS @ de alae problema an tatarvale [i J] Lab de{AJE)) = eevee teil rams = (3, 4, 5 0] INTERVAL DP ORDER Cia jam Wsisj Practice Daily, Get Batter, Be Unstoppable! re | YAP Master the Patterns, Solve Ang. Problem! PAGE 12 i. WHY DP ON GRIDS? + Many petame ork oa 20 gra, + We move from tap-lefe (0,0) te bebtom-right [n-2, m-1). * Allowed moves: Right (+) and Down (4). + Optimal substructure + Oerkapping aubprotlems + Use DP Me mach call (5, j), the onever | deperats. on calls (e-4, DD and |G p-4D only. 5. C++ CODE - UNIQUE PATHS dass Solution { public: ink wriquePatheLink my int nd { che Cemcar tlanng apteMEj] = dpli-adt + apClti-s fC return dp{m-1][n-1]; } hs 8, MIN PATH SUM ~ DP TABLE (Example) Grid DP ON GRIDS Unique Paths, Min Poth Sum & More! gy 2. UNIQUE PATHS (Count Paths) 3, DP DEFINITION Problem: Count the number of unique paths From (0,0) te Cn-dym-2) when you can only move Right or Down. Let dpli}Lj)] = sumbar of unique paths to reach coll (i, j) : from (0, 0). Exanplet n= 3, m= 3 L J s|—|—]4 Transition: vital | Ast 4pCeIGj] = dpli-2)0i) + pCi Ij-4] PRRs 6 (from tap * trom left) Ed Ba we | Baus Cases: paths Lt I=|-Le 5+ apLo}fo} + 4 (starting call) + For First cow Cie O)e apCOJEj] = 4 + Foe First ealume Kj +O) dpfiJ[0] = 2 6. MINIMUM PATH SUM Problem: Gietn & grid of non-negative ewmbers, find a path from (0,0) te Crodyen2) such thot Une sum of rumbers in the path is minimum. Example a} 3]a Lette blame lien) 2 os fa 7 Neca the coment Hin Sum atala j SPag ————~ | Pe Ded (Right + Right + Den + Dawn} 9. Cee CODE - MIN PATH SUM snes Solution [ 410. VARIATIONS ON GRIDS @ Unique Paths with Obstacles + Sere alls wre Macked (-1). © gridQilLj] in Vecked + dgfiIEj] = 0. —|—} @ Mesimam Path Sum in Tangle + Sinar Uden tak fs btangalar arid, @D Masini Path Sum + Replace eniel.) sith mel © Cont Pathe with Stops Um 3D DF dp IES DER) = wage be resch (5) fb atape, D Cherry Pickup CheetGode Fi) OD parse geng Foo stark te and ot 3D DF, i) 1] 4) 4 i 1 2 3 z| 4] 3 |[e] + Each call + sur of bop + laft, + Bollom-right call (2,2) = 6 oka unique pothe. 7. DP DEFINITION [ek dpliDEj] = minimum path sum ty reach call (i, j) from (0, 0), Transition: ebpLiQLJ] = geileDL)) + eivledp 10050, del]-21) (freon top or From left) Bane Conan » @e€0KCe) = grialo}to) + Feat cme dgfGTL] + aefoltj-a] + griafoItj] Beak eta: dof i]C0] * dele A100] + gril ILO] ak eeinPathSnml ueckertvackartinkshE grid} { Mele Ink ns griduaiaa(), m= graf). siaa(); wacker Crusher tink?» dpln, vactercinto(m, 0); Tine Complatity: dplONo) = gialo}o), On & m) Ferink jo4s jim, jee) MONG) = dplOILG-2) » grill 0]C4 I: i 9 aLiITOT = aefi-t0C0] + grafsTtoy, | Sees Comet May 0) Ofn * =) + jim jee) r grldQi ML) © inCdedinA]Lj), dpQi Nj AD; Can be eptimined to Ole} er On). pte delet — —_ »% 41. SPACE OPTIMIZATION (FOR MIN PATH SUM) 5 x] Instead of 2D DP, use 1D array: 7 ia x 7 wether int? dele: Neo sts! 40] = gridLo][o | for Cink j=4; j ‘UGered for large grids) le ei] = dplj-4] + getsLOILj] _ _ fer Gok When te Use DP on Grids? 4p{0] 1 a Magen’ fer Cink jm t E Del Rights Laatieal So Start Lp) = mieldptg], pf)-20) + gated, | Mev tien pelh mem B= Ent ) ww Count paths Ca 1 Of With/Whthouk slstacles return apf 4]; Of Mulki-dimensional grids. 12, PRACTICE PROBLEMS 13. COMMON MISTAKES /f\, 44, MEMORY TRICK cb) 15. INTERVIEW Instat fica BONUS FORMULA Th 62. Unique Pathe ee een Tp + lleh ake Grid DF ce wary, common in Cag (2 63. Unique Paina TT Xt Kheg bilan 7 Sig Oo alarviows TF no sbrlacdes, Se, ‘aman Me Unig et inated oF in - - || Seater aak Humber of Unique Paths HO. al i er HF Bad 2 oggentty a FEI 42. nim falling Poth om § ae ie a A 2 Wella Leenatblana Clatma2, ant) EE ars. Deegan Gore aed en pape inde ne ae (Combinskions) I WA. Cherry Pickup He Mek teeing sleacles property pl as + Oplinize space Sf nended eg : ] PRO Trp Drew the grid, define your state, Find the branainn, sot base canes, (OF Grids + DP = P. ful C inakion! é n. and tulld OP table slap by slap! a. PALINDROME PARTITIONING — Prablain ‘we use 20 DP to check if mubatring DP ON STRINGS Palindrome Partitioning & Wildcard Matching

2 cut te (Othe partitions gine mara cute) 7. DP DEFINITION & TRANSITION 8. EXAMPLE = WILCDARD DP TABLE per ye wacker Cwuclar dhael>> pall, etcar sults, 2: fer Link ie OL ic my weed [ s a a 6b uit) = df maw eae : fe fot f 1 Hj HDL aut: 0 eae / | 4 aCe] = Go 0) 70: minleafil, 1+ wtH1]), ) i oe ’ f ra * ait-o 4 © return extant) cami teati}eaen > 6, WILDCARD MATCHING Binblams: Gin ring ond pation p eminining sildeards “7? matches ony single char) and“ retin nny teguance vlading empl), daterming AF pattern matihes entire string. Example: a+ “abefedgiaacdfimda” pt “abted isda” Use 2D DF where dpfiJ[j] = dows Aewarer: True, a(0..i-2] match plO..j-1] ? 9. Ce# CODE - WILCDARD MATCHING ales Baltics | de(iJ)] = true af of Ott] matches pl. j-2] a= Take (ned) =| Tseaileen Ae eo) "Vie Ghiaatias apakiued 4 4) 1F pfje-2] too latter <6 a et 4 ete Soa etal vector twectertheal?® dened, rackorthool Met Falaa)}: a0 + Steal aD ate PT se 2) UF jal o- 7 fi bbe ui a mai CI) + a o/tl/relelele (pint) o= "6 pCOIGD = dpCOIC-21, fer Gah be Pern a 9 ea] ao/Fi/[t{]ti]ele ACTED = dplDp-20 Ce etches empty Hdpli-tIL] Cot matenan one mere che) «db | OF | OF] oT] | OF eect fuera weiss eee F G@l-2] 20 FU pl] Base Cases: e F F T T ahah atheiseeee + dpfo](0] = true F | Fle|t|re ane oe Tenet Onto Space: Diam = aple]Ej) = GEO. 5-2) ore att #9 + dplsJO) = Fela for tO 40. OTHER STRING DP PROBLEMS eiteranees [A Palindrema Substring (Leabode 5) For odd length: [Longest Palindromic Subteqeence (516) a boe (A Distinct Subeequances (115) ? a TH Count Palinatromnic Subsirings (647) Fer evan, length (I Wideard Matching (44) 5 7 : (Regular Expression Mashing (10) ra A] Seramble String (87) a Understand the pater, draw the DP table, "I PRO TIP > Fil bose cones Firsk, than transitions! apl4]04] = trun + Match! 24. TRICK — EXPAND AROUND CENTER r Pe Unahl for: Longast Polindoamic Subatying, ? ot Ln Colors tm OCA?) time, OC2) paca) = J apEsJEj) ~ Futon , raturn defn Jl], 13, COMMON MISTAKES Falindroms Partitioning X Forgaiting hou cases gn 6 & & 3 Handling. '*" tncommectly J] a 2 Mok precompating palindrome table ‘ = Ve 2X Ofibyrona in indices Loa ew Using , . ; 4 fh | 14, WHEN TO USET . . b F of Palindrome problems + 20 DF or Expand Arwurdh Cenber Wf Fallen matching + 2D DP Wf Ag sabstring property + 20 OF Strings Hide Patkerns, Dpslieveels the Solstiog! cr _* "+ PAGE 15 | DP + TREES ieee Tree DP (Example: House Robber III) ip — « rab tis vote 1. PROBLEM - HOUSE ROBBER ITT 2, INTUITION 3. BP STATE DEFINITION Use children's rasa to compas. Geren = Winery tres, ech vile tne AR each mode, san hewn 2 choices: fer each rede, maleiain tue : some monty 44. STATE TRANSITION 5 1) Rob this mile + cannot vob the children Rekurn the masimam manag you ean a TF era thie nade: alka saan hicaacsteea acon 2) Ship thin nada = children con be dpfreda)[0) = man moray fer a Sr ow reba or shipped fo WD ak ce ead geld dp[reda] [0] © anda- val Fsaenple Tras: + dp[teft][0] + dpfright][0] + Wa oben this from beta (ehildeen) | dpCneda) 2] = set mirage children carmel be mobbed) te Up (rout) | 00 wah Ute rede oo as L J @ ge WF we ship this ede: i | Think F- aa is a, ‘ol do Ab eomry, anda: Return: max(dpfroct](O), alpfroot}(1}) | dplreda] [0] = sauldpLiaAt](0], apftereI00]) srabveda]) = nede- onl. + shig[ loft] + ship[right ] + manldpLright ILO), deLsghtL2]) stigfnee] + meclr{lert], [leh ]) | Gabtudrer samt robbed or uhipyd) Anawert 7 (Rob 3 + 3 -* 4) | + maxtrabfright], sbigLright]) é ® (2) (3) (aah skip = mantlefls dip, Ueflirah) © men(right-ship, rightorse) Gren-Cieh Subir Sun roe + nede= oval + lafleship + righl skip 5. VISUAL = POST-ORDER TRAVERSAL (Botlom -» Tap) 6. C++ CODE (DFS + Post-order) For wach nada chew: (skip, rob) class Solution { 43, 3) f ree Pesk=seder, stapat vactordink> dfelTreaNodet moda) { at in a if Ctnoda) ature (0, O}; Mf {akip, rob} (4, 2) (4, 9) ae Unie (dip, oA) ute lefk = dfalnode->Left); 4, A pair . ute right * dfe(ode->right); eee ink skip © max(lafi[O], laft(1]) + max(eight[O], right 1]); i 44) Finally ob rook + bale mae ink rob = node-pval + left[0] + right[0); 3) 0, 1) (0, 1) ™ ————— reluen (skip, rob]; Noa | Velua aft Cabin ab) Righk abort? ahpfrods) | rade] Explanalion, } a 3 0.0) 40,0) ® 3 baal dip ®, mei-al a 1 0.01 wor 7] 1 fa int rob TreeNode* root) { aja 0.01 ta.0) ® 1 tw Sis pate AEA) a a way C22) meshavementnaies) Bee aoz sib aaa ays ely a] an meager | Seeeaes ) a4 ta 2 au ease % . 7 . Time Complenity: O(N} | Final Answer = manlskig[root), rob[ract]) = max(7, 8) = & | | (ob modes: 3 -+ 2's children (3H -4) and right Length © 3 > Length * 4 [ts ta] vo Matrix Chain Mulbiplication dpLi]Lj] = min Teej — ¥ Burst Balloons r idk. hea )l] i ky j ae ee oe CAE + pee TEGD + coats td) From Leaf Values t t t Polygon THongulation Conk to wolve Conk be olen Conk be mainly left, interval right terval the toa parks Ay | Ag | Aa | Ag | Ag [i,k] Chea, j7 ak a | i . Coed i [Foo Tip TR, Eoery pose oplit K mat be triad! | (&) MATRIX CHAIN MULTIPLICATION EXAMPLE S) DRY RUN TABLE (are = (40, 30, 5, 60]) Let arr = [40, 30, 5, 60] (n= 3 mabrices) n= 3 mobrices + indices: 1 2 3 Mekrices: TJLj] = min cost be multiply matrices from Ai to A Ay* 10% 300 ps 3055 Ape Sn 6O ae? Se i 4 Two ways be parenthesize: thy 4 2 3 ®@ ((AAz) Aa) Cost = 10-30-5 + 10«5<60 4 0 4500 4500 Pee | | AL A i es Le | | Legend i Ly (40-30) « (3045) = does r a | eat 3 ns | Le (1025) x (5260) = 10-60 ead DOS gore 3 -.9 p00 i | AL (AAA: | @ (Ar(AzAa)) 3 i | Aa As Goat « 3045460 + 19*30-60) (3005) « (5x60) = 3060 = 9000 + 18000 to Le eat » (30560) = 10=60 are Answer = dpf1][3] = 4500 Minimum cost = 4500 @ INTERVAL SPLIT VISUAL %) C++1% CODE (MATRIX CHAIN MULTIPLICATION) We want dpl1][4] (example with 4 motrices) Smetana pie 5 ERG is ae, er pee eee int n © arraiéel) = 4 7 ramiete a6 matrlsas veutercvertercint>> dpined, wecterciats(asd, 0)); Splik oh k= A Split at k= 2 Spit ak k= 3 Hf Van = Length of inbervel for Ci len = 2; mon tel wa) [bal bal) [al tal] [lea hidacte pail oe RH ink j= te len - 45 pCi] 5] = INT_MAX; oft she (22)) [B8)) 80) | fe2]) f.a)) | 23] for (int k= i; ke j- 1 se | jis int cost = dpliJCk] + dpfkei] are{i-1] + arr[k] « ili Ba est 4eCCIEET = rsinddpE CCT, seet)s ) ie pl 41E0; } HF Usoge: wectortint? arr = (10, 30, 5, 60}; #f cout << matrinChoinMultiplication{arr) << "\n";) // Output: 4500 Try every cplit point k in [i, j-1] * and take minimum, 4 (8) COMPLEXITY (3) INTERVIEW TRICKS (4G) COMMON MISTAKES (EL) PRACTICE PROBLEMS Tem Complesitys (NA) | “ Se B tee es Bet X Filling DP row-wiae (wrong order), Sf Matrix Chain Mulliplication (LC 10) {3 nested temps) | oe aca : Wrong interval length / bounds. of Baersh Balloons (LE 942) Space Complexity: O(N?) | kes : Not kryjng all aplit points. & Minimum Score Triangulation (LC 1039) wv Tr eile ik (DP table) a a Troorract indices in cost formula of Minimum Coat Tres From Leaf Values Wrong rwltiptication cost (Le 1130) faerfi-t] + arefk] + afi) LN ~—-----=- - . O's Memory INTERVAL DP = Pick Interval —» Try Every Split -» Combine Left + Right -» Take Best ‘ G5) — (loop k) {add costs) (minimum) “VA | } xx KOK zaill (PAGE 18 DP + GAME THEORY — =~ + Players play optimally. Optimal Play (Minimax DP) & + Vou bey be masinize your score, + Oppanant also plays optimally, Trick: dp[i] = max(score - dp[next]} + Use DP + Minimax. 1. WHAT IS DP + GAME THEORY? 2, CORE IDEA & FORMULA 3. MINIMAX GAME TREE VISUAL + Too players take burns, & From pesilien’\i, youpich ona! neve, [any [8,530 | + ach planer plea optimally + Opponent will play optimally from nant stats . ° he mauimlnn alr stare, = Vaur asara = poinks you git ame = «Ral geal: sanienine your sesre apponant’s bask scora from nask, saasumlng oppanerl. alae (playa ab Gide ae optimally. ae | deCiD © Hanimn, stare, francs ‘ fees the current player can achieve Wo Pick fram Ends (LC $86) ___ ee ¥ Shane Gama. rr z v Colne in aw Line deli] © mam Wakafi) = dp [nant], Uakali) = epfnent2]. ..)) Vv Degue Game ‘we || t i - Many More! Y ore yes taka nee oyprmantie beak from. next stake - oo 77 Peo Tip Tt, iz ¥ Rook value +23 —+ bask score difference the starting player can achieve. Think in kerma of “score differance” (Current Player - Opponent) L J \ 4. EXAMPLE ~ PICK FROM ENDS 5. DRY RUN (ap[i] = max(acore ~ do[next])) 6. Ces CODE (PICK FROM ENDS) | Array: 8, 45, 3, 72 | 7 eee Tun Rama | apts) teptarenen ink selvetvactersint>& name) { ink n= numensize(); a te i iui ese atalar 30 f-O07 7-0-7 F Orly ana lament veutercint> dp(a + 1, 0); J dela] © 0 : For (ink Ge n= Ay i> at + Each wanks le maximise their tobal. 2| a-o-3 2 | meta) 5 te atten nett als Bh ink bakeRight = ruma[i] - dpli + 2 eee rer 2 | a8 apf} a2 8-48) e812 melazsys a Tool Sum 841543475 33 ay as] aad pli] © max(takeleft, takeRight); Ty dpf0] = 23 (best scare difference), 1 B-dplt] s+ T-dplt} = -5 23 rant-4, -s)+ + than firsk player's seore = (33423) /2= 28 ink total = occuulate(muma.begin(), numsend(), 0}; — - return (hobol + dp[O]) / 2) J¥ First player man score || p00) = Ze <5 Bact ners difteranen fer fink ployer’ | | t (te oct) le ee i | | Spacer OCH) 7. HOW IT WORKS? 8. GENERAL FORMULA (VERY IMPORTANT) 9. (OTHER GAME DP EXAMPLES + You pick & number. i. 5 oe a) dp[i] + mas Problem ‘Shake Transition Iden, = Opponent. will lene you in the F | wtota where his advantage ix Shona Game ple] La] Pick Uf J right, miniminn opponent i score if pick option! - dp[nexti], score iF pick option? - dpfnext?], Dogue Game ple] C3] Fick from anda Mele already kms thet advantage ing dplneet] . Goina in Linn | dpfSIE5] | Flak ann oniny opponent plahs nad 3 \ J Bis pant ecteintoge Krom) current shee: Ramu Bones pL [r][k] Remme + marge same calaen hake - aeeranee ~ dpfnant] | . i Nels tapi] = beak score differance from state i rs dele] ee Sp 0= lous Gp) = scare iF pick sption = pinta ya gn Granta # dp(aaxt] = appenant’s bert from nant state 10. GAME TREE MINI EXAMPLE 12. COMPLEXITY 12. COMMON MISTAKES 13, PRACTICE PROBLEMS oe B aneig See ay a 0 Pick from Ends (LO 486) r a a" x oe | nok cet dilFareeue (uc e77) Ot) ‘OtN) >< Forgetting spponant also plays L as optimally. Coins in a Line (Gon be optimised te OC1) Ath careful ending) v Of Stone Game TI (LC 1140) ¢ ¢ Deque Gama Pick Now + Opponent Plays - You Get Left ry MEMORY MAXIMIZE YOUR TRICK Score Now - Opponent’s Best = Your Advantage PAGE 19 A DYNAMIC PROGRAMMING PROBLEM we HOW TO IDENTIFY Recognize the Pattern Before Writing the Code vy 2. WHAT MAKES A PROBLEM DP? TA Overlapping Sebpilent multiple (5) gre (4) #03) iat NO an Repeaked ay) GQ) Ga) te ral i NN Tt ” OP optimal answers of amolller problems, “santti0) | “a ™ Beatl7) + Bent) ~. a Final Answer 4, PROBLEM TYPE + DP PATTERN 2. DP IDENTIFICATION FLOWCHART (soa) ? 3. KEYWORDS - THINK DP! Tf you see these words in a problem, think about DP. Can tha problam be broken into smaller similar probleme? a IT'S PROBABLY DP! | ep a eat . aa Ketan Min} | (Humber of Maye) | (Teun / Fabs) Find marcrwms # | Count total ways Chask if something rrinimun somathing,| Le de something. is pausible wr valid Example: Example Example: Masirars Sire Gling Sirs Retin Egan neramsing, Salve. Su. Coin Change 5. HOW TO THINK? (5 STEP METHOD) a 2 ae) Sa te mask, ron, column, he.) Define the State Lak the Choices Tdertify the peremater (inden, pesikion, Whab will ee shored in def] # pl LI) 7 | MAK MIN Largest, cmallact, best, optimal NUMBER OF WAYS umys, how many ways, sounk, umber of ways, tolal umys TRUE / FALSE rue, false, velid, possible, + is posaible SUBSEQUENCE feet) sepewce, pelindrone), ues, Lis, em sequence SUBARRAY ¢ SUBSTRING ] subarray, substring, continusus, sum of subarray, maximum subarrey ‘OTHER COMMON SIGNALS divide, split, Form, include / exclude | Sequence DP | Subarray DP Gri OP Tree DP | Interval, DP Digit DF | {Sabsaquance} (Conbirwsoe) | ,| ell] | 2Es3Ts A Dives jd 129 Find longest / Bash teontirmmras Het in gah Weck on bree, Sela an range Marbars with, hath eebsepearan, | park. ¢ anbarrag. | wlth cmmairaiets, | urushares G10 ¢ herate. | dig contrainte cs, LES, Edt Kedane’s Alge Unigua Paths House Rebber TIE | Matrix Chain Counk numbers Distance Max Subarray Finimam faith Sam | ‘Tres Diameter | Multiplication | slthenk 3 6 QUICK EXAMPLE - CLIMBING STAIRS Problem: Tn how many ways can you climb te the top WF you can take 1 or 2 steps? @ What changes Current. position (2) ® Stale pLi] = murbur of wage be reach abap | | Step 3 ; 5») Che yo oak Sm range Ecos aay ahead Fron int (lake d stay) or ed taba 2 ans) || Write Transition Transition ers How be mare From carrent sabe pCi] = dpfi-2] + dpfi-2] | be next stoke? ©) Bese Cane dp(O] = 1 Cone amy be stay ok start) om Base Case dpfi} = 1 C4 step) GED Se ae DF Tabla / Rawk: , ae = EE i | Fallow these atapa and you can solve e (nos @ a a ‘nnn ——— _Anawer fer ns BoB 4. MEMORY TRICK “MAX or MIN? 5 DP IDENTIFICATION CHECKLIST Can the praesent Laka aren inllar problema? NUMBER of WAYS? [Bl De these srallar protons rapsah? TRUE or FALSE? BB Can we there ard, route the, enters? SUBSEQUENCE / SUBARRAY? [Deus the anawer depend an prarioan rumulhe? @ CHOICES + REPEATED STATES? Dyas Seely ed 7 Di eee Gf THINK DYNAMIC PROGRAMMING!" ap a 1s ES ys = Use DPE | SBP “IF the future depends on the past, you're probably looking at Dynamic Programming.” 7. DP vs GREEDY a cl a A Guarentens optional ‘es: Coden, corrack) ae alas arena anmer ‘COMMON MISTAKES Wreng tala definition Tnaerraat transition Wreng base sass Nat handling adga cosas Forgetting overlapping subproblans, Wrong ilarakion order (in tabulation) Tnlagar overflow KAR KK KH * 14. PRACTICE SUGGESTIONS Start with Fibonecci problemas Tey Grid DP questions Pid ras qn De String DP problems Move to advanced DP (Trex, Digit, Practice, Pattern, Perfect! ere Bikmask))