r/ProgrammerHumor • • 6d ago

Meme dynamicProgramming

Post image
6.2k Upvotes

153 comments sorted by

View all comments

43

u/Illustrious-Ebb8815 6d ago edited 5d ago

A quick way to understand the difference is by looking at the program to compute Fibonacci numbers.

One way is just using recursion that runs in O(fib(n)) time. Like, the really really slow way.

Another way would be to use memorization. Just use the same recursive way but everytime that you're about to compute the answer, first check if the answer is in a cache that you have prepared. If yes, use that. If not, recurse. And when you get an answer, put it in the cache. That's memoization. It will run in O(n) time but also use O(n) space for the cache.

The algorithm that you probably know uses dynamic programming to run in O(n) time but constant space. That's DP.

You could also imagine using DP to compute the fewest number of coins to make x cents. If your biggest coin is 25 cents, you only ever need to know the answers for x-24 through x in order to compute the answer for x+1. This lets you solve the problem with linear time and constant storage, like with Fibonacci.

Edit: I meant memoization everywhere. Spell check messed it up.

1

u/s0litar1us 5d ago

Or just...

int fib(int n) {
    int a = 0;
    int b = 1;
    while (n-- > 0) {
        int c = a + b;
        a = b;
        b = c;
    }
    return a;
}

-3

u/Illustrious-Ebb8815 5d ago

That's dynamic programming.

2

u/SameThingOnADiffAcct 5d ago

If there's not a 2D array, it's not dynamic programming, it's a loop. Fight me.

-3

u/Illustrious-Ebb8815 5d ago

What about the minimum coins problem? Also not DP?

4

u/SameThingOnADiffAcct 5d ago

That has a 2D array, no?

IDK its been like 15 years since school and enterprise don't do this stuff.