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.
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.
O(logN) != O(1)