|
| 1 | +var solve = function(rb, fc, i, j, dp) { |
| 2 | + if (i >= rb.length) return 0; |
| 3 | + if (j >= fc.length) return Infinity; |
| 4 | + |
| 5 | + if (dp[i][j][fc[j][1]] !== -1) return dp[i][j][fc[j][1]]; |
| 6 | + |
| 7 | + let notTake = solve(rb, fc, i, j + 1, dp); |
| 8 | + let take = Infinity; |
| 9 | + |
| 10 | + if (fc[j][1] > 0) { |
| 11 | + let distance = Math.abs(rb[i] - fc[j][0]); |
| 12 | + fc[j][1]--; // Decrement capacity temporarily |
| 13 | + take = distance + solve(rb, fc, i + 1, j, dp); |
| 14 | + fc[j][1]++; // Restore capacity |
| 15 | + } |
| 16 | + |
| 17 | + dp[i][j][fc[j][1]] = Math.min(take, notTake); |
| 18 | + return dp[i][j][fc[j][1]]; |
| 19 | +} |
| 20 | +var minimumTotalDistance = function(robot, factory) { |
| 21 | + robot.sort((a, b) => a - b); |
| 22 | + factory.sort((a, b) => a[0] - b[0]); |
| 23 | + |
| 24 | + let dp = Array.from({ length: robot.length }, () => |
| 25 | + Array.from({ length: factory.length }, () => |
| 26 | + Array(101).fill(-1) |
| 27 | + ) |
| 28 | + ); |
| 29 | + |
| 30 | + return solve(robot, factory, 0, 0, dp); |
| 31 | +}; |
0 commit comments