Optimized DP
It was hard for me to see that this is a DP solution. \n\nI was not sure if previous computations can be reused. \n\nTurned out they can, but only if we process
It was hard for me to see that this is a DP solution. \n\nI was not sure if previous computations can be reused. \n\nTurned out they can, but only if we process elements in the order of `n2`, increasing.\n\n**C++**\nBecause we only look one step back, we can optimize the memory to `dp[1001]`.\n\n```cpp\nint minimumTime(vector<int>& n1, vector<int>& n2, int x) {\n    int sum1 = accumulate(begin(n1), end(n1), 0);\n    int sum2 = accumulate(begin(n2), end(n2), 0);\n    int dp[1001] = {}, n = n1.size();\n    vector<int> ids(n1.size());\n    iota(begin(ids), end(ids), 0);        \n    sort(begin(ids), end(ids), [&](int i, int j){ return n2[i] < n2[j]; });\n    for (int i = 1; i <= n; ++i)\n        for (int j = i; j > 0; --j)\n            dp[j] = max(dp[j], dp[j - 1] + n2[ids[i - 1]] * j + n1[ids[i - 1]]);\n    for (int t = 0; t <= n; ++t)\n        if (sum1 + sum2 * t - dp[t] <= x)\n            return t;\n    return -1;\n}\n```
['C']