כיצד לבנות ולקודד אלגוריתמי תכנות דינמיים

אולי שמעת על זה בהכנה לראיונות קידוד. אולי נאבקת בזה בקורס אלגוריתמים. אולי אתה מנסה ללמוד כיצד לקודד לבד, ואמרו לך איפשהו בדרך שחשוב להבין תכנות דינמי. שימוש בתכנות דינמי (DP) לכתיבת אלגוריתמים הוא חיוני לא פחות מכפי שחושש ממנו.
ומי יכול להאשים את אלה שמתכווצים מזה? תכנות דינמי נראה מאיים מכיוון שהוא לא מלמד. מדריכים רבים מתמקדים בתוצאה - הסבר על האלגוריתם, במקום התהליך - מציאת האלגוריתם. זה מעודד שינון, לא הבנה.
במהלך שיעור האלגוריתמים שלי השנה, חיברתי את התהליך שלי לפתרון בעיות שדורשות תכנות דינמי. חלקים ממנו מגיעים מהפרופסור שלי לאלגוריתמים (שמגיע לו הרבה קרדיט!), וחלקים מהניתוח שלי של אלגוריתמי תכנות דינמיים.
אבל לפני שאשתף את התהליך שלי, בואו נתחיל עם היסודות. מה זה בכלל תכנות דינמי?
תכנות דינמי מוגדר
תכנות דינמי מסתכם בפירוק בעיית אופטימיזציה לבעיות משנה פשוטות יותר, ואחסון הפיתרון לכל תת-בעיה כך שכל תת-בעיה תיפתר פעם אחת בלבד.
למען האמת, הגדרה זו עשויה שלא להיות הגיונית לחלוטין עד שתראה דוגמה לבעיית משנה. זה בסדר, זה עולה בסעיף הבא.
מה שאני מקווה להעביר הוא ש- DP היא טכניקה שימושית לבעיות אופטימיזציה, אותן בעיות שמחפשות את הפתרון המקסימלי או המינימלי בהינתן אילוצים מסוימים, מכיוון שהיא בודקת את כל בעיות המשנה האפשריות ולעולם אינה מחשב מחדש את הפתרון לכל תת-בעיה. זה מבטיח נכונות ויעילות, שאיננו יכולים לומר על רוב הטכניקות המשמשות לפתרון או קירוב של אלגוריתמים. זה לבדו הופך את DP למיוחדת.
בשני הסעיפים הבאים אסביר מהי בעיית משנה , ואז יניע מדוע אחסון של פתרונות - טכניקה המכונה memoization - חשוב בתכנות דינמי.
בעיות משנה על בעיות משנה על בעיות משנה
בעיות משנה הן גרסאות קטנות יותר של הבעיה המקורית. למעשה, לעיתים קרובות בעיות משנה נראות כמו גרסה מחדש של הבעיה המקורית. אם מנוסחים כראוי, בעיות משנה בונות זו על זו על מנת להשיג את הפתרון לבעיה המקורית.
כדי לתת לך מושג טוב יותר על האופן שבו זה עובד, בואו ונמצא את בעיית המשנה בבעיית תכנות דינמית לדוגמא.
העמיד פנים שחזרת בשנות החמישים לעבוד על מחשב IBM-650. אתה יודע מה זה אומר - קלפים! התפקיד שלך הוא לגבר או אישה את IBM-650 למשך יממה. אתה מקבל מספר טבעי n punchcards לרוץ. יש להריץ כל קלף א ' בשעה התחלה קבועה מראש s_i ולהפסיק לפעול בזמן סיום קבוע מראש f_i . רק כרטיס ניקוב אחד יכול לרוץ ב- IBM-650 בבת אחת. לכל כרטיס ניקוב יש ערך משויך v_i בהתבסס על חשיבותו לחברה שלך.
בעיה : כאחראי על IBM-650, עליך לקבוע את לוח הזמנים האופטימלי של כרטיסי ניקוב שממקסם את הערך הכולל של כל כרטיסי הפונצ'ר.
מכיוון שאעבור את הדוגמה הזו בפירוט רב לאורך מאמר זה, אני אקניט אותך רק עם בעיית המשנה שלה לעת עתה:
בעיית משנה : לוח הזמנים הערכי המקסימלי עבור קלפי אגרוף i עד n כך שכרטיסי האגרוף ממוינים לפי זמן התחלה.
שימו לב כיצד תת-הבעיה מפרקת את הבעיה המקורית לרכיבים הבונים את הפתרון. עם בעיית המשנה, אתה יכול למצוא את לוח הזמנים המקסימלי לערכים עבור כרטיסי ניקוב n-1 עד n ולאחר מכן עבור כרטיסי ניקוב n-2 עד n , וכן הלאה. על ידי מציאת הפתרונות לכל בעיית משנה אחת, תוכל להתמודד עם הבעיה המקורית עצמה: לוח הזמנים הערכי המקסימלי עבור קלפים 1 עד n . מאחר שתת הבעיה נראית כמו הבעיה המקורית, ניתן להשתמש בבעיות המשנה כדי לפתור את הבעיה המקורית.
בתכנות דינמי, לאחר שתפתור כל אחת מבעיות המשנה, עליך לזכור או לשמור אותה. בואו נגלה מדוע בסעיף הבא.
הנעה מניע עם מספרי פיבונאצ'י
כשאומרים לו ליישם אלגוריתם המחשב את ערך פיבונאצ'י עבור כל מספר נתון, מה היית עושה? רוב האנשים שאני מכיר היו בוחרים באלגוריתם רקורסיבי שנראה כך בפייתון:
def fibonacciVal(n): if n == 0: return 0 elif n == 1: return 1 else: return fibonacciVal(n-1) + fibonacciVal(n-2)
אלגוריתם זה משיג את מטרתו, אך במחיר עצום . לדוגמה, בואו נסתכל על מה האלגוריתם הזה צריך לחשב על מנת לפתור n = 5 (בקיצור F (5)):
F(5) / \ / \ / \ F(4) F(3) / \ / \ F(3) F(2) F(2) F(1) / \ / \ / \ F(2) F(1) F(1) F(0) F(1) F(0) / \ F(1) F(0)
העץ שלמעלה מייצג כל חישוב שיש לבצע על מנת למצוא את ערך פיבונאצ'י עבור n = 5. שימו לב כיצד תת פותרת בעיית המשנה עבור n = 2 שלוש פעמים. לדוגמא קטנה יחסית (n = 5), זה הרבה חישובים חוזרים ונשנים, מבוזבזים!
מה אם במקום לחשב את ערך פיבונאצ'י עבור n = 2 שלוש פעמים, יצרנו אלגוריתם המחשב אותו פעם אחת, שומר את הערך שלו וניגש לערך פיבונאצ'י המאוחסן עבור כל התרחשות עוקבת של n = 2? זה בדיוק מה שעושה תזכורת.
עם זאת, כתבתי פתרון תכנות דינמי לבעיית הערך של פיבונאצ'י:
def fibonacciVal(n): memo = [0] * (n+1) memo[0], memo[1] = 0, 1 for i in range(2, n+1): memo[i] = memo[i-1] + memo[i-2] return memo[n]
שימו לב כיצד הפתרון של ערך ההחזרה מגיע מתזכר מערך ההזכרות [], אותו ממלא איטרטיבי על ידי לולאת ה- for. על ידי "איטרטיבי", אני מתכוון שמזכר [2] מחושב ומאוחסן לפני תזכיר [3], תזכיר [4], ... ותזכיר [ n ]. מכיוון שהתזכיר [] מלא בסדר זה, ניתן לפתור את הפתרון לכל תת-בעיה (n = 3) על ידי הפתרונות לבעיות המשנה הקודמות שלה (n = 2 ו- n = 1) מכיוון שערכים אלה כבר נשמרו ב תזכיר [] במועד מוקדם יותר.
משמעות השמירה אינה חישוב מחדש, מה שמביא לאלגוריתם יעיל יותר. לפיכך, תזכורת מבטיחה שתכנות דינמי יעיל, אך היא בוחרת בעיית משנה נכונה שמבטיחה שתוכנית דינמית עוברת את כל האפשרויות בכדי למצוא את הטובה ביותר.
כעת, לאחר שעסקנו בתזכירים ובעיות משנה, הגיע הזמן ללמוד את תהליך התכנות הדינמי. אבזם פנימה.
תהליך התכנות הדינמי שלי
שלב 1: זיהוי תת הבעיה במילים.
לעתים קרובות מדי, מתכנתים יפנו לכתיבת קוד לפני שהם יחשבו בצורה ביקורתית על הבעיה העומדת על הפרק. לא טוב. אסטרטגיה אחת לירות את המוח שלך לפני שאתה נוגע במקלדת היא שימוש במילים, באנגלית או אחרת, כדי לתאר את בעיית המשנה שזיהית במסגרת הבעיה המקורית.
אם אתה פותר בעיה הדורשת תכנות דינמי, קח פיסת נייר וחשוב על המידע הדרוש לך כדי לפתור בעיה זו. כתוב את בעיית המשנה בזאת.
לדוגמא, בבעיית האגרוף, הצהרתי כי ניתן לכתוב את בעיית המשנה כ"תזמון הערך המקסימלי לכרטיסי אגרוף i עד n כך שכרטי האגרוף ימוינו לפי זמן התחלה. " מצאתי את בעיית המשנה הזו בכך שהבנתי שכדי לקבוע את לוח הזמנים הערכי המקסימלי עבור כרטיסי חבטה 1 עד n כך שכרטי המחץ ימוינו לפי זמן התחלה, אצטרך למצוא את התשובה לבעיות המשנה הבאות:
- לוח הזמנים של הערך המקסימלי עבור כרטיסי ניקוב n-1 עד n כך שהכרטיסיות ממוינות לפי זמן התחלה
- לוח הזמנים של הערך המקסימלי עבור כרטיסי ניקוב n-2 עד n כך שהכרטיסיות ממוינות לפי זמן התחלה
- לוח הזמנים של הערך המקסימלי עבור כרטיסי ניקוב n-3 עד n כך שהכרטיסיות ממוינות לפי זמן התחלה
- (וכו ')
- לוח הזמנים הערכי המקסימלי עבור קלפים 2 עד n כך שהכרטיס ממוין לפי זמן התחלה
אם אתה יכול לזהות בעיית משנה שמתבססת על בעיות משנה קודמות כדי לפתור את הבעיה בהישג יד, אתה בדרך הנכונה.
שלב 2: כתוב את בעיית המשנה כהחלטה מתמטית חוזרת.
Once you’ve identified a sub-problem in words, it’s time to write it out mathematically. Why? Well, the mathematical recurrence, or repeated decision, that you find will eventually be what you put into your code. Besides, writing out the sub-problem mathematically vets your sub-problem in words from Step 1. If it is difficult to encode your sub-problem from Step 1 in math, then it may be the wrong sub-problem!
There are two questions that I ask myself every time I try to find a recurrence:
- What decision do I make at every step?
- If my algorithm is at step i, what information would it need to decide what to do in step i+1? (And sometimes: If my algorithm is at step i, what information did it need to decide what to do in step i-1?)
Let’s return to the punchcard problem and ask these questions.
What decision do I make at every step? Assume that the punchcards are sorted by start time, as mentioned previously. For each punchcard that is compatible with the schedule so far (its start time is after the finish time of the punchcard that is currently running), the algorithm must choose between two options: to run, or not to run the punchcard.

If my algorithm is at stepi, what information would it need to decide what to do in stepi+1? To decide between the two options, the algorithm needs to know the next compatible punchcard in the order. The next compatible punchcard for a given punchcard p is the punchcard q such that s_q (the predetermined start time for punchcard q) happens after f_p (the predetermined finish time for punchcard p) and the difference between s_q and f_p is minimized. Abandoning mathematician-speak, the next compatible punchcard is the one with the earliest start time after the current punchcard finishes running.
If my algorithm is at stepi, what information did it need to decide what to do in stepi-1? The algorithm needs to know about future decisions: the ones made for punchcards i through n in order to decide to run or not to run punchcard i-1.
Now that we’ve answered these questions, perhaps you’ve started to form a recurring mathematical decision in your mind. If not, that’s also okay, it becomes easier to write recurrences as you get exposed to more dynamic programming problems.
Without further ado, here’s our recurrence:
OPT(i) = max(v_i + OPT(next[i]), OPT(i+1))
This mathematical recurrence requires some explaining, especially for those who haven’t written one before. I use OPT(i) to represent the maximum value schedule for punchcards i through n such that the punchcards are sorted by start time. Sounds familiar, right? OPT(•) is our sub-problem from Step 1.
In order to determine the value of OPT(i), we consider two options, and we want to take the maximum of these options in order to meet our goal: the maximum value schedule for all punchcards. Once we choose the option that gives the maximum result at step i, we memoize its value as OPT(i).
The two options — to run or not to run punchcard i — are represented mathematically as follows:
v_i + OPT(next[i])
This clause represents the decision to run punchcard i. It adds the value gained from running punchcard i to OPT(next[i]), where next[i] represents the next compatible punchcard following punchcard i. OPT(next[i]) gives the maximum value schedule for punchcards next[i] through n such that the punchcards are sorted by start time. Adding these two values together produces maximum value schedule for punchcards i through n such that the punchcards are sorted by start time if punchcard i is run.
OPT(i+1)
Conversely, this clause represents the decision to not run punchcard i. If punchcard i is not run, its value is not gained. OPT(i+1) gives the maximum value schedule for punchcards i+1 through n such that the punchcards are sorted by start time. So, OPT(i+1) gives the maximum value schedule for punchcards i through n such that the punchcards are sorted by start time if punchcard i is not run.
In this way, the decision made at each step of the punchcard problems is encoded mathematically to reflect the sub-problem in Step 1.
Step 3: Solve the original problem using Steps 1 and 2.
In Step 1, we wrote down the sub-problem for the punchcard problem in words. In Step 2, we wrote down a recurring mathematical decision that corresponds to these sub-problems. How can we solve the original problem with this information?
OPT(1)
It’s that simple. Since the sub-problem we found in Step 1 is the maximum value schedule for punchcards i through n such that the punchcards are sorted by start time, we can write out the solution to the original problem as the maximum value schedule for punchcards 1 through n such that the punchcards are sorted by start time. Since Steps 1 and 2 go hand in hand, the original problem can also be written as OPT(1).
Step 4: Determine the dimensions of the memoization array and the direction in which it should be filled.
Did you find Step 3 deceptively simple? It sure seems that way. You may be thinking, how can OPT(1) be the solution to our dynamic program if it relies on OPT(2), OPT(next[1]), and so on?
You’re correct to notice that OPT(1) relies on the solution to OPT(2). This follows directly from Step 2:
OPT(1) = max(v_1 + OPT(next[1]), OPT(2))
But this is not a crushing issue. Think back to Fibonacci memoization example. To find the Fibonacci value for n = 5, the algorithm relies on the fact that the Fibonacci values for n = 4, n = 3, n = 2, n = 1, and n = 0 were already memoized. If we fill in our memoization table in the correct order, the reliance of OPT(1) on other sub-problems is no big deal.
How can we identify the correct direction to fill the memoization table? In the punchcard problem, since we know OPT(1) relies on the solutions to OPT(2) and OPT(next[1]), and that punchcards 2 and next[1] have start times after punchcard 1 due to sorting, we can infer that we need to fill our memoization table from OPT(n) to OPT(1).
How do we determine the dimensions of this memoization array? Here’s a trick: the dimensions of the array are equal to the number and size of the variables on which OPT(•) relies. In the punchcard problem, we have OPT(i), which means that OPT(•) only relies on variable i, which represents the punchcard number. This suggest that our memoization array will be one-dimensional and that its size will be n since there are n total punchcards.
If we know that n = 5, then our memoization array might look like this:
memo = [OPT(1), OPT(2), OPT(3), OPT(4), OPT(5)]
However, because many programming languages start indexing arrays at 0, it may be more convenient to create this memoization array so that its indices align with punchcard numbers:
memo = [0, OPT(1), OPT(2), OPT(3), OPT(4), OPT(5)]
Step 5: Code it!
To code our dynamic program, we put together Steps 2–4. The only new piece of information that you’ll need to write a dynamic program is a base case, which you can find as you tinker with your algorithm.
A dynamic program for the punchcard problem will look something like this:
def punchcardSchedule(n, values, next): # Initialize memoization array - Step 4 memo = [0] * (n+1) # Set base case memo[n] = values[n] # Build memoization table from n to 1 - Step 2 for i in range(n-1, 0, -1): memo[i] = max(v_i + memo[next[i]], memo[i+1]) # Return solution to original problem OPT(1) - Step 3 return memo[1]
Congrats on writing your first dynamic program! Now that you’ve wet your feet, I’ll walk you through a different type of dynamic program.
Paradox of Choice: Multiple Options DP Example

Although the previous dynamic programming example had a two-option decision — to run or not to run a punchcard — some problems require that multiple options be considered before a decision can be made at each step.
Time for a new example.
Pretend you’re selling the friendship bracelets to n customers, and the value of that product increases monotonically. This means that the product has prices {p_1, …, p_n} such that p_i ≤ p_j if customer j comes after customer i. These n customers have values {v_1, …, v_n}. A given customer i will buy a friendship bracelet at price p_i if and only if p_i ≤ v_i; otherwise the revenue obtained from that customer is 0. Assume prices are natural numbers.
Problem: You must find the set of prices that ensure you the maximum possible revenue from selling your friendship bracelets.
Take a second to think about how you might address this problem before looking at my solutions to Steps 1 and 2.
Step 1: Identify the sub-problem in words.
Sub-problem: The maximum revenue obtained from customers i through n such that the price for customer i-1 was set at q.
I found this sub-problem by realizing that to determine the maximum revenue for customers 1 through n, I would need to find the answer to the following sub-problems:
- The maximum revenue obtained from customers n-1 through n such that the price for customer n-2 was set at q.
- The maximum revenue obtained from customers n-2 through n such that the price for customer n-3 was set at q.
- (Et cetera)
Notice that I introduced a second variable q into the sub-problem. I did this because, in order to solve each sub-problem, I need to know the price I set for the customer before that sub-problem. Variable q ensures the monotonic nature of the set of prices, and variable i keeps track of the current customer.
Step 2: Write out the sub-problem as a recurring mathematical decision.
There are two questions that I ask myself every time I try to find a recurrence:
- What decision do I make at every step?
- If my algorithm is at step i, what information would it need to decide what to do in step i+1? (And sometimes: If my algorithm is at step i, what information would it need to decide what to do in step i-1?)
Let’s return to the friendship bracelet problem and ask these questions.
What decision do I make at every step? I decide at which price to sell my friendship bracelet to the current customer. Since prices must be natural numbers, I know that I should set my price for customer i in the range from q — the price set for customer i-1 — to v_i — the maximum price at which customer i will buy a friendship bracelet.
If my algorithm is at stepi, what information would it need to decide what to do in stepi+1? My algorithm needs to know the price set for customer i and the value of customer i+1 in order to decide at what natural number to set the price for customer i+1.
With this knowledge, I can mathematically write out the recurrence:
OPT(i,q) = max~([Revenue(v_i, a) + OPT(i+1, a)])
such that max~ finds the maximum over all a in the range q ≤ a ≤ v_i
Once again, this mathematical recurrence requires some explaining. Since the price for customer i-1 is q, for customer i, the price a either stays at integer q or it changes to be some integer between q+1 and v_i. To find the total revenue, we add the revenue from customer i to the maximum revenue obtained from customers i+1 through n such that the price for customer i was set at a.
In other words, to maximize the total revenue, the algorithm must find the optimal price for customer i by checking all possible prices between q and v_i. If v_i ≤ q, then the price a must remain at q.
What about the other steps?
Working through Steps 1 and 2 is the most difficult part of dynamic programming. As an exercise, I suggest you work through Steps 3, 4, and 5 on your own to check your understanding.
Runtime Analysis of Dynamic Programs
Now for the fun part of writing algorithms: runtime analysis. I’ll be using big-O notation throughout this discussion . If you’re not yet familiar with big-O, I suggest you read up on it here.
Generally, a dynamic program’s runtime is composed of the following features:
- Pre-processing
- How many times the for loop runs
- How much time it takes the recurrence to run in one for loop iteration
- Post-processing
Overall, runtime takes the following form:
Pre-processing + Loop * Recurrence + Post-processing
Let’s perform a runtime analysis of the punchcard problem to get familiar with big-O for dynamic programs. Here is the punchcard problem dynamic program:
def punchcardSchedule(n, values, next): # Initialize memoization array - Step 4 memo = [0] * (n+1) # Set base case memo[n] = values[n] # Build memoization table from n to 1 - Step 2 for i in range(n-1, 0, -1): memo[i] = max(v_i + memo[next[i]], memo[i+1]) # Return solution to original problem OPT(1) - Step 3 return memo[1]
Let’s break down its runtime:
- Pre-processing: Here, this means building the the memoization array. O(n).
- How many times the for loop runs: O(n).
- How much time it takes the recurrence to run in one for loop iteration: The recurrence takes constant time to run because it makes a decision between two options in each iteration. O(1).
- Post-processing: None here! O(1).
The overall runtime of the punchcard problem dynamic program is O(n) O(n) * O(1) + O(1), or, in simplified form, O(n).
You Did It!
Well, that’s it — you’re one step closer to becoming a dynamic programming wizard!

One final piece of wisdom: keep practicing dynamic programming. No matter how frustrating these algorithms may seem, repeatedly writing dynamic programs will make the sub-problems and recurrences come to you more naturally. Here’s a crowdsourced list of classic dynamic programming problems for you to try.
So get out there and take your interviews, classes, and life (of course) with your newfound dynamic programming knowledge!
Many thanks to Steven Bennett, Claire Durand, and Prithaj Nath for proofreading this post. Thank you to Professor Hartline for getting me so excited about dynamic programming that I wrote about it at length.
Enjoy what you read? Spread the love by liking and sharing this piece. Have thoughts or questions? Reach out to me on Twitter or in the comments below.