man.god96's blog

By man.god96, history, 4 years ago, In English

This is regarding https://leetcode.com/problems/coin-change/. It is a simple DP problem. And I wrote the following code for it using map for memoization. But it gave Time limit extended -

class Solution {
public:
    int coinChange(vector<int>& coins, int amount) {
        int n = coins.size();
        map<int,int> dp;
        dp[0]=0;
        for(int i=1;i<=amount;i++) {
            dp[i]=amount+1;
            for(int j=0;j<n;j++) {
                if(i>=coins[j]) dp[i] = min(dp[i],dp[i-coins[j]]+1);
            }
        }
        return dp[amount]>amount ? -1:dp[amount];        
    }
};

But when I changed map to vector, it gets ACCEPTED (Following code got accepted)-

class Solution {
public:
    int coinChange(vector<int>& coins, int amount) {
        int Max = amount + 1;
        vector<int> dp(amount + 1, Max);
        dp[0] = 0;
        for (int i = 1; i <= amount; i++) {
            for (int j = 0; j < coins.size(); j++) {
                if (coins[j] <= i) {
                    dp[i] = min(dp[i], dp[i - coins[j]] + 1);
                }
            }
        }
        return dp[amount] > amount ? -1 : dp[amount];
    }
};

So why map gave TLE and not vector. When should we use map and when vector while solving DP problems? Any help will be appreciated.

  • Vote: I like it
  • -14
  • Vote: I do not like it

| Write comment?
»
4 years ago, # |
  Vote: I like it +2 Vote: I do not like it

In a map, all operations (accessing an element, creating a new element, etc.) take $$$O(\log n)$$$ time to execute (where $$$n$$$ is the size of the container). In a vector, the same operations take $$$O(1)$$$ time.

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

O(logN) != O(1)