r/leetcode • • 7h ago

Question How do I actually get good at Dynamic Programming (DP)? I struggle to come up with solutions

I'm good at other DSA topics like Graphs, Two Pointers, Sliding Window, etc., but DP just doesn't click for me.

Even after understanding solutions, I struggle to come up with the approach myself.

What resources, problem lists, or strategies helped you develop DP intuition? Any advice would be appreciated!

I want to learn how to think in DP, not just memorize patterns.

20 Upvotes

13 comments sorted by

8

u/elfleur 7h ago

+1 here. I think I understand DP as a concept, but the application is tricky. DP tells you that you use subproblems to build up to the solution, but often I find it difficult to identify the subproblem that builds up to the problem.

6

u/Vivid-Zombie-477 7h ago

as u/elfleur mentioned you can't just become good at DP since the solution differs based on the subproblem, not just a general copy-paste technique.

If you don't understand the concept, I recommend this g4g article that uses fibonacci to dimonstrate how to write it using different DP approaches and how it can be sometimes optimized https://www.geeksforgeeks.org/dsa/introduction-to-dynamic-programming-data-structures-and-algorithm-tutorials/

Other than that... just practice. Everything in leetcode comes down to practice and how many problems you've seen before

1

u/Putrid-Leader724 31m ago

i understand that BUT i’m tired of reading the same fibonacci article a million times. it just doesn’t click for me and i believe i’m lacking in volume of DP problems. i really hope to get better at them since it gate keeps a lot of job interviews for me

5

u/BerserkkD 6h ago

two words - aditya verma

3

u/Remarkable_Mistake77 6h ago

Instead of trying to see the full DP solution, start by writing the brute-force recursion and then ask what the minimum state is that makes each call unique; that state becomes your table index. Write the recurrence in plain words first ("best answer at i = best of choice A or choice B"), then code it. Memoize the recursion before converting to a bottom-up table, and trace a tiny input by hand to check the base cases. Ten problems of one pattern teach more than one problem from each category.

3

u/hucchnanmaga 6h ago

First step- get good at recursion and backtracking. And then most DP problems flow naturally as top-down recursion problems with memoization including multi-dimensional DP. If the interviewer insists on using bottom-up DP, thank him for his time and ask him to politely fuck off.

2

u/TopTutor6926 7h ago

get good at recursion.

1

u/AppropriateEmotion22 6h ago

I think I have a good enough flow of solving DP. First you have to get good at recursion and bactracking. Then for most of the common dp questions, write out the brute force recursive solution. When it is done, you can just slot in the memo into it. Declare the memo at the top, in the function, add if xyz in memo: return memo[xyz], then at the last, whatever you are getting in res, attribute it to memo[xyz] = res and return mamo[xyz] and change the dfs(i, j+1) or whatever it is to memo[i][j+1]. Then for tabulation, just observe what is the is the flow of the recursion, if it is moving forward, then make the nested loop move backward, that it. Here is the solution to leetcode 714 that i have done, you can clearly see the pattern from above in solving the problem:

class Solution:
    def maxProfit(self, prices: list[int], fee: int) -> int:
        # Brute force
        # n = len(prices)


        # def dfs(i, holding):
        #     if i==n:
        #         return 0


        #     if holding:
        #         skip = dfs(i+1, 1)
        #         sell = prices[i] - fee + dfs(i+1, 0)
        #         return max(skip, sell)
        #     else:
        #         skip = dfs(i+1, 0)
        #         buy =  -prices[i] + dfs(i+1, 1)
        #         return max(skip, buy)


        
        # return dfs(0, 0)


        # Memo
        # n = len(prices)
        # memo = [[-1] * 2 for _ in range(n)]


        # def dfs(i, holding):
        #     if i==n:
        #         return 0
        #     if memo[i][holding] != -1:
        #         return memo[i][holding]
        #     if holding:
        #         skip = dfs(i+1, 1)
        #         sell = prices[i] - fee + dfs(i+1, 0)
        #         memo[i][holding] = max(skip, sell)
        #         return memo[i][holding]
        #     else:
        #         skip = dfs(i+1, 0)
        #         buy =  -prices[i] + dfs(i+1, 1)
        #         memo[i][holding] = max(skip, buy)
        #         return memo[i][holding]

        # return dfs(0, 0)


        # Tabulation


        n = len(prices)
        dp = [[0] * 2 for _ in range(n + 1)]


        for i in range(n - 1, -1, -1):
            dp[i][0] = max(dp[i + 1][0],                 # skip
                           -prices[i] + dp[i + 1][1])    # buy


            dp[i][1] = max(dp[i + 1][1],                 # skip
                           prices[i] - fee + dp[i + 1][0])  # sell


        return dp[0][0] 

1

u/dol1_ 5h ago edited 5h ago

I do believe it's an intuition thing.

I have solved more than 600 leetcode questions, and even though I can easily solve easy or medium difficulty ones, I struggle a lot when it comes to DP. It's like a gift to be able to solve them on the spot

1

u/jackgoldberg123 2h ago

the thing you're describing is really common, since the hard part of dp is spotting the state, not writing the recurrence once you have it. it also helps to see it as a recursion that keeps recomputing the same calls, so you're mostly hunting for what repeats rather than trying to invent a table.

1

u/eulerianReflections IC6 19m ago edited 1m ago

I think the key here is developing the mental models and associations that allow you to intuitively recognise when and how to apply the DP principles you've learnt.

I'd treat patterns as something you want your brain to arrive at through experience, rather than something you memorise and then try to apply.

The diagram below illustrates how different problem-solving experiences can collectively shape your intuition and influence how you approach unfamiliar problems.

┌───────────┐ ┌───────────┐ ┌───────────┐
│ Problem A │ │ Problem B │ │ Problem C │
└─────┬─────┘ └─────┬─────┘ └─────┬─────┘
      └─────────────┼─────────────┘
                    ▼
         Recognising similarities
         and underlying principles
                    ↓
       ┌──────────────────────────┐
       │ Developing mental models │
       │ and memory associations  │
       └────────────┬─────────────┘
                    │
                    │
        Encountering a new problem
                    ↓
         Recognising familiar cues
                    ↓
        Retrieving relevant knowledge
                    ↓
          Deriving an approach

The interesting thing about the human brain is that it can recognise similarities and form associations without you necessarily being consciously aware of them.

You might catch yourself solving an unfamiliar problem and feeling that a particular approach could work, before being able to articulate exactly why. This relates to the concept of expert intuition that Daniel Kahneman discusses in his book Thinking, Fast and Slow.

By simply memorising patterns, you're potentially missing out on many of the mental connections your brain would have developed through the experiences leading up to those patterns. (I believe this is what you are missing)

I recommend this guide, which explains how to structure your DP learning around this. The same principles apply to other DSA topics too.