classSolution{ public: longlongintoptimalKeys(int N){ queue<array<longlongint,3>> q; unordered_map<longlongint, int> vis; q.push({1, 1, N - 1}); longlongint res = 0; while(!q.empty()) { array<longlongint, 3> alli3 = q.front(); q.pop(); longlongint a = alli3[0], cp = alli3[1], n = alli3[2]; if(n == 0) { res = max(res, a); continue; } if(!vis.count(a + cp) or vis[a + cp] < n - 1) { q.push({a + cp, cp, n - 1}); vis[a + cp] = n - 1; } if(n >= 3and (!vis.count(a + a) or vis[a + a] < n - 3)) { q.push({a + a, a, n - 3}); vis[a + a] = n - 3; } } return res; } };
Time : O(n)
Space : O(n)
As the number of A’s become large, the effect of pressing Ctrl-V more than 3 times starts to become insubstantial as compared to just pressing Ctrl-A, Ctrl-C and Ctrl-V again.
So We just calculate last 3 copy & paste operation