Why using map giving TLE, but with vector it's ACCEPTED?

Revision en1, by man.god96, 2020-04-04 22:04:13

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.

Tags c++, dynamic programming

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en1 English man.god96 2020-04-04 22:04:13 1464 Initial revision (published)