• + 2 comments

    O(N*M)

    int twoRobots(int M, int N, vector<vector<int>> queries) {
        vector<vector<int>> cache(N, vector<int>(M+1, INT_MAX));
        set<int> endStates = {0};
        cache[0][0] = abs(queries[0][1] - queries[0][0]);
        for (int i=1; i < N; i++) {
            for (int x : endStates) cache[i][x] = cache[i-1][x] + abs(queries[i][0] - queries[i-1][1]) + abs(queries[i][1] - queries[i][0]);
            int temp = INT_MAX;
            for (int y : endStates) {
                if (y != 0) temp = min(temp, cache[i-1][y] + abs(queries[i][0] - y) + abs(queries[i][1] - queries[i][0]));
                else temp = min(temp, cache[i-1][y] + abs(queries[i][1] - queries[i][0]));
            }
            cache[i][queries[i-1][1]] = min(cache[i][queries[i-1][1]], temp);
            endStates.insert(queries[i-1][1]);
        }
        return *min_element(cache[N-1].begin(), cache[N-1].end());
    }